Some time ago, I updated a recruitment requirement for senior iOS interviewers, which received many likes and attention from my friends. Many of you may already be hiring or applying for a job with some of the interview tips I’ve provided in that article! Here should everybody request, provide relevant answer to the interview question inside! I believe that both the interviewer and the job seeker will learn something ~~

PS: the space is a little long, you can pay attention to or like the collection for a rainy day!!

IOS based

1: Tell me your understanding of atomic & nonatomic

  • Atomic operations have no guarantee of thread safety. beatomicThe modified properties (which do not overload setters and accessors) only guarantee the integrity of reads and writes to data, that is, atomicity, but not the thread-safety of the object.
  • 2, thread safety is guaranteed, the performance requirements can be usednonatomicalternativeatomicOf course, you can use it all the timeatomic.
  • 3: detailed reference

2: What happens to weak objects when they are released? How is it done? You know sideTable? Can I draw the structure inside?

Weak objects are set to nil when released, as opposed to assign;

The Runtime maintains a weak table that stores all the weak Pointers to an object. The weak table is a hash table where Key is the address of the pointer to the weak object and Value is an array of addresses of the pointer to the weak object.

  • 1. Initialization:runtimeWill be calledObjc_initWeak functionInitializes a new oneWeak pointerThe address pointing to an object.
  • 2. Add a reference:Objc_initWeak functionWill be calledObjc_storeWeak () function.objc_storeWeak()Update pointer pointer to create the corresponding weak reference table.
  • 3, release when calledClearDeallocating function.ClearDeallocating functionFirst get all based on the object addressWeak pointer address, and then iterate through the array and set its data tonilAnd finally put thisentryWeak tableDelete, and finally clean up the object’s record.
  • 4: detailed reference
struct SideTable {
    // Ensure the atomic operation of the spin lock
    spinlock_t slock;
    // Reference count hash table
    RefcountMap refcnts;
    // weak references the global hash table
    weak_table_t weak_table;
}

struct weak_table_t {
    // Store all weak Pointers to the specified object
    weak_entry_t *weak_entries;
    // Storage space
    size_t    num_entries;
    // participate in judging the reference count auxiliary
    uintptr_t mask;
    // Maximum hash key offset
    uintptr_t max_hash_displacement;
};
Copy the code

3: What does block look like? The strong can?

  • blockItself is as good as an objectretain, andrelease. However,blockAt creation time, its memory is allocated on the stack, not on the heap. Its own domain is created at the time of creation, and calling a block outside the scope of creation causes the program to crash.
  • useretainYes, but the retain behavior of a block is implemented with the copy behavior by default
  • becauseblockVariables are declared as stack variables by default. In order for them to be used outside of the declaration domain of a block, the stack variable is declared as a stack variableblockCopy to the heapblockProperty declaration is consistent with the actual operation, preferably declared ascopy.
  • A detailed reference

4: Why can blocks capture external variables? What does __block do?

To study the capture of external variables of Block, it is necessary to remove function parameters. The following is an analysis based on the capture of these four variable types.

  • Automatic variables
  • A static variable
  • Static global variable
  • The global variable

Global variables global_i and static_global_j increase in value and are captured by the Block. This is easy to understand because they are global and have a wide scope. After capturing them, the Block does ++ in the Block. After the Block ends, their values can still be saved.

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  __Block_byref_a_0 *a; // by ref
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, __Block_byref_a_0 *_a, int flags=0) : a(_a->__forwarding) { impl.isa = &_NSConcreteStackBlock; impl.Flags = flags; impl.FuncPtr = fp; Desc = desc; }};Copy the code

This is how the __main_block_IMPL_0 structure captures automatic variables. That is, when a Block syntax is executed, the values of the automatic variables used by the Block syntax expressions are stored in an instance of the Block structure, that is, in the Block itself.

It’s worth noting here that if you have a lot of automatic variables outside of the Block, static variables, etc., those variables are not used inside the Block. These variables are not captured by the Block, that is, their values are not passed into the constructor.

The Block captures external variables only for values that are needed inside the Block closure. It does not capture values that are not needed.

5: Talk about your understanding of the transmission and response chains of events

  • A: responder chainUIResponserIt includes all kinds of thingsTouch messageSuch as start, move, stop and so on. commonUIResponserUIView and subclass.UIViController.APPDelegate.UIApplicationAnd so on.

So let’s go back to the response chain, the response chain is made up of UIResponser, so according to what rules.

  • A: An application that starts UIApplication generates A singleton and associates it with an APPDelegate. The APPDelegate is set up as the root of the entire response chain, and UIApplication will link itself to this singleton, that is, the UIApplication nextResponser(the next event handler) as APPDelegate.

  • When any UIWindow is created, the nextResponser inside the UIWindow will be set as a UIApplication singleton. RootViewController UIWindow is initialized, the rootViewController nextResponser will be set to UIWindow

  • C: UIViewController initializes the loadView and the nextResponser of the VC view will be set to VC.

  • D: addSubView During addSubView operation, if the subView is not the VC View, the nextResponser of the subView will be set to superView. If it’s a VC View, it’s subView -> subview. VC ->superView. If subview. VC is released in the middle, it’s subview. nextResponser = superView

We use a realistic scenario to explain what happens when a user clicks a button on the screen.

    1. When the user touches the screen, the system hardware process will obtain the click event, encapsulate the event and store it in the system. Since the hardware detection process and the current App process are two processes, port communication is used to transfer events between the two processes. The hardware detection process will place the event inAPPThe port that was tested.
  • 2.APP starts the main thread RunLoop and registers a port event to detect the occurrence of touch events. When the event arrives, the system invokes the RunLoop of the main thread of the current APP. The source is the App main thread event, which is analyzed by the main thread.

  • 3. Finally, the system determines whether the touch caused a new event, that is, whether the first finger touched. If so, the system will first look for the response chain in the response network. If not, the event is a Touch Message from an ongoing event, which means there is already a saved response chain

  • Two: event delivery chain

There are two ways to do this.

SubViews - (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event; - (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event; // default returns YESif point is in bounds
Copy the code
  • A: process

  • Alpha >0.01 2. UserInteractionEnabled == YES 3. Hidden = NO

  • 2: Check whether the change point is inside the view.

  • 3: If the child view is iterated then continue to return responsive views until there are none.

  • B: Common problems

  • The parent view is not clickable. Can the child view be clickable

  • No, the hit test ends when it reaches the parent view

  • Setting the child view to be unclickable does not affect the parent view

  • Overwriting the parent view does not affect clicking

  • The effect of gestures on the responder method

  • C: Practical usage

  • Click on a circular control to achieve only clicking on a circular area effectively, reload pointInside. In this case, the external points can also be judged as internal points, and vice versa.

  • Event response chain can communicate between different controls in complex functional interface, which is easier than proxy and block in some scenarios

6. Talk about the understanding of KVC and KVO?

  • The use and principle of KVC and KVO
  • Detail key value observation (KVO) and its implementation mechanism
  • KVC/KVO principle detailed explanation and programming guide

7: What does RunLoop do? Is its inner workings understood?

  • What is Runloop?
  • Deep understanding ofRunLoop | Garan no dou

Literally meaning “message loop, runloop”, a runloop is essentially a do-while loop that listens for various event sources and messages, manages them and dispatches them to threads for execution.

  • 1. Notify the observer that the run loop is about to enter. There is a one-to-one correspondence between threads and runloops

  • 2. Notify the observer that the timer will be processed.

  • 3. Notify the observer that any non-port-based input source is about to fire.

  • 4. Trigger any non-port-based input sources that are ready to trigger.

  • 5. If the port-based input source is ready and waiting to be triggered, handle the event immediately. Go to step 9.

  • 6. Notify the observer that the thread is about to fall asleep.

  • 7. Put the thread to sleep until one of the following events occurs:

    • The event reaches the port-based input source.
    • The timer runs.
    • The timeout value set for the run loop expires.
    • The run loop is explicitly awakened.
  • 8. Notify the observer that the thread has been awakened.

  • 9. Handle pending events.

    • If a user-defined timer is triggered, the timer event is processed and the loop is restarted. Go to step 2.
    • If the input source is fired, the event is passed.
    • If the run loop is explicitly awakened but has not timed out, restart the loop. Go to step 2.
  • 10. Notify the observer that the run loop has exited.

8: how does apple implement autoreleasepool?

Arc is optimized by the compiler

void *context = objc_autoreleasePoolPush(); // the code in {} is objc_autoreleasePoolPop(context);Copy the code
  • To a structureAutoreleasePoolPageTo write an object that needs to be released automatically, similar to a flag, calledobjc_autoreleasePoolPop(context)After, will put this intermediate objectreleaseOnce in a while.
  • The important thing here is, how does the method return value get automatically freed?
  • Its useThread Local Storage (TLS)Thread-local storage is stored in or taken out of a thread each time.
  • We didn’t unload{}Automatically release objects in eachrunloopAt the end of the release, equivalent to a largeautoreleasepoolIn the.
  • Refer to the article
  • How does apple implement autoreleasepool

9: Talk about your understanding of FRP (functional responsiveness) and extend to RxSwift or RAC!

Reference article :RxSwift (1) — A Preliminary look at this article is enough! Then combine RxSwift to map to RAC! The idea of functional responsiveness is constant! As for the internal packaging is different, but in the end it is all the same!

10: Have you ever played Instrument in normal development?

  • Instruments Performance testing
  • Apple’s official Website — Instruments User Guide

Analysis: The content here is very interesting, for an iOS senior developer, I think there is a very important grasp! Especially for 3-5 years of development, if you don’t master these contents, I think it is not qualified

My personal advice is to master the interview questions at the same time also need more job seekers to analyze and expand! For example, your exploration ideas, you unexpectedly extended this knowledge point. And your landing of the actual development process! And that’s all a plus!

Runtime

1: What is ISA and what does ISA do?

  • Refer to the article

2: What does an instance object’s ISA point to? What does the class object point to? What does metaclass ISA point to?

  • Refer to the article
  • Instance objectisaPointing to the class
  • The class objectisaPointing to the metaclass
  • The metaclass ISA points to the root metaclass

  • 3: What are the essential differences and connections between class methods and instance methods in ObjC?

  • Refer to the article

Methods:

  • 1. Class methods belong to class objects
  • 2. Class methods can only be called from class objects
  • 3. Self in the class method is the class object
  • 4. Class methods can call other class methods
  • 5. Member variables cannot be accessed in class methods
  • 6. Object methods cannot be called directly from class methods

Instance methods:

  • 1. Instance methods belong to instance objects
  • 2. Instance methods can only be called from instance objects
  • 3. Self in the instance method is the instance object
  • 4. Member variables can be accessed in instance methods
  • 5. Call instance methods directly from instance methods
  • 6. Class methods can also be called from instance methods (by class name)

4: The difference between load and initialize?

+load

  • 1, as soon as the program starts, all the code of the class will be loaded into memory (before the main function executes), put in the code area (whether the class is used or not will be called).
  • 2,+loadMethod is called once and only when the current class is loaded into memory
  • 3. When both parent and child classes are implemented+loadMethod, the parent class is called first+loadMethod, and then call the subclass’s+loadmethods
  • 4, load the original class first, then load the classified+loadmethods
  • 5. When subclasses are not implemented+loadMethod, the parent class is not called+loadmethods
  • 6. Multiple classes are implemented+loadMethod,+loadMethod call order, andCompile SourcesIn the same order

The load method is described in the Official Apple documentation

+ the initialize

  • Called the first time a class is used (when a class object is created)
  • 2,initializeMethods are called only once during the entire program’s run, no matter how many times you use the class
  • 3,initializeA one-time initialization of a class
  • Call the parent class firstinitializeCall the subclass’sinitialize
  • 5. When subclasses are not implementedinitializeMethod will inherit the implementation of the parent class to call again, again the previous parent classinitializeThe method is called first
  • 6, when there are multipleCategoryImplement theinitializeMethod, which overrides the methods in the class and executes only one (executesCompile SourcesLast one on the listCategory 的initializeMethods)

The Initialize method is described in the Official Apple documentation

5: What does the _objc_msgForward function do? What happens when you call directly?

This function is called for method forwarding when the object does not implement a method. (Corresponding to a methodIMPI didn’t find it. It will return this functionIMPTo perform)

  • 1. Call the resolveInstanceMethod: method to allow the user to dynamically add an implementation to the Class at this point. If there is an implementation, it is called and returned. If not, proceed with the following action.
  • 2. Call forwardingTargetForSelector: method, trying to find a can respond to the message object. If it gets it, it forwards it directly. If nil is returned, proceed with the following action.
  • 3. Call methodSignatureForSelector: method, trying to get a method signature. If not, call doesNotRecognizeSelector directly to throw an exception.
  • 4. Call the forwardInvocation method, which wraps the method signature from step 3 into the Invocation Invocation.

If you call this method directly, even if the method you want to call is implemented, it will not be called and will go directly to the message forward step.

6: Briefly describe the process of calling methods in Objective-C

  • Objective-CIs a dynamic language, where each method is dynamically converted to message sending at runtime, i.e. :objc_msgSend(receiver, selector), the whole process is described as follows:
  • objcWhen sending a message to an object,runtimeThe library finds the class that the object actually belongs to based on its ISA pointer
  • It then looks for methods to run in the list of methods in that class and in the list of methods in its parent class
  • If, at run time, the program hangs and throws an exception if no corresponding method is found in the topmost parent class (usually NSObject)unrecognized selector sent to XXX
  • But before that, the runtime of ObjC gives three chances for the saviors to crash, and all three of them are illustratively problematicWhen is an exception called for an unrecognized selector?The instructions in

PS: Runtime makes Objective-C a dynamic language, and makes C an object-oriented language. Classes, objects and their corresponding methods can be created, checked, and modified during program running. These operations can be implemented using the corresponding methods in Runtime.

7: Can you add instance variables to the compiled class? Can I add instance variables to classes created at run time? Why is that?

  • 1. You cannot add instance variables to compiled classes
  • 2. Can add instance variables to classes created at run time

Explanation:

  • 1. The compiled class is registered in theruntimeIn the class structureobjc_ivar_listThe linked list sum of instance variablesinstance_sizeThe memory size of the instance variable has been determined,runtimeWill be calledclass_setvarlayoutclass_setWeaklvarLayoutTo deal withstrong weakSo you cannot add instance variables to an existing class
  • 2. Classes created at runtime can be added to instance variables, calledClass_addIvar function.but is callingobjc_allocateClassPairAfter that,objc_registerClassPairBefore, for the same reason.

Tell me about your understanding of aspect programming

Aspect-oriented programming (AOP) is a term used in computer science to refer to a programming paradigm. The paradigm is based on a language construct called facets, a new modularity mechanism for describing crosscutting concerns scattered across objects, classes, functions, etc. Refer to the article

Analysis: Runtime this module iOS interview no matter junior high school will interview. I think this module is more than just asking about knowledge content, I would like to hear job seekers climb the pit to explore the xinli journey! Runtime this module is the key to page development!

Network & Multithreading

1: What are the drawbacks of HTTP?

HTTP has these major shortcomings, as listed below.

  • Communications use clear text (not encryption) and the content can be eavesdropped
  • The identity of the communicating party is not verified, so it is possible to encounter camouflage
  • The integrity of the message could not be proved, so it may have been tampered with

These problems occur not only over HTTP, but also over other unencrypted protocols.

2: Talk about three handshakes, four waves! Why three handshakes, four waves?

I think this place still needs self-understanding, with their own words to express it!

3: The difference between a socket connection and an Http connection

httpIs based onsocketOf the above.socketIt’s a complete settcp,udpProtocol interface.

  • The HTTP protocol: Simple object Access protocol, corresponding to the application layer,HTTPThe protocol is based on TCP connections.
    • TCP: corresponds to the transport layer.
    • IP protocol: corresponds to the network layer.

TCP/IP is a transport layer protocolThe HTTP protocol is an application-layer protocol and mainly deals with how to package data.

Socket is the encapsulation of TCP/IP. It is not a protocol, but an interface to call TCP/IP.

  • HTTP connection: is the so-called short connection, that is, the client sends a request to the server, the server responds to the connection will be broken.
  • Socket connection: the so-called long connection, in theory, the client and the server once established the connection will not be actively broken, but due to various environmental factors may make the connection disconnected.

HTTP is a request made by a client using THE HTTP protocol. When sending a request, the HTTP request header must be encapsulated and the request data bound. The server usually has a Web server to cooperate with the request. In HTTP request mode, the client initiates a request and the server responds to it. After a request is completed, the server disconnects from the client to save resources. The server cannot actively respond to the client. The main class used by the iPhone is NSUrlConnection. A socket is used to connect the client to the server directly. There is no provision for disconnection after the connection. Therefore, the client and the server can keep the connection, and both sides can actively send data. It is usually used in game development or stock development where there is a lot of immediacy and a lot of data to keep sending. The main class is CFSocketRef.

  • UDP: indicates the user datagram protocol. It is mainly used in places that require high real-time performance and low quality. However, high-quality lines are prone to packet loss.
  • TCP: is a transmission control protocol, is connection-oriented, and the operating environment must require its reliability, packet loss and good congestion control mechanism.

4: HTTPS, the latest security layer in addition to SSL? What additional parameters does the client send first in a parameter handshake

5: When did POP network and Alamofire encapsulation network URLSession need Moya?

POP Networks: Protocol-oriented programming networks can greatly reduce coupling! The network layer sinks and the service layer rises. The middle is separated by Moya of POP network. It doesn’t matter if your project is RxSwift function responsive! Because there are RxMoya

Reference article:

  • Moya
  • Swift – Protocol Oriented Programming (POP)
  • Swift – When Moya meets RxSwift (Network Architecture Optimization)

6. How to implement dispatch_once

+ (instancetype)sharedInstance
{
    /* Define static variables for the corresponding class instance; Meaning: Static variables are defined within a function. No matter how many times the function is called, they are initialized only once in memory, and the last assigned value */ is saved
    static ClassName *instance = nil;
    /* Define a dispatch_once_t static variable that identifies whether the following block of dispatch_once has been executed. The static modifier initializes it to 0 by default, and blocks are executed when the value is 0. When the block completes, the underlying layer sets the onceToken to 1, which is why the address of the onceToken is passed (static variables can change the value of the onceToken by address), and locks the method to make it thread-safe */
    static dispatch_once_t onceToken;
    /* Block is executed only when onceToken == 0, otherwise the static variable instance*/ is returned
    dispatch_once(&onceToken, ^{
        instance = [[ClassName alloc] init];
        / /...
    });
    return instance;
}
Copy the code

The basic implementation of CGD-Dispatch_once for iOS

Can I write a read/write lock? Talk about specific analysis 8: When does a deadlock occur? How to avoid it? 9: What kinds of locks are there? How do they work? What’s the difference between them? It’s best to use it in context

  • Several methods of iOS read and write lock
  • 11 Locks in iOS Development and performance comparisons
  • Refer to the article

Analysis: This module may be a dead end for the average developer. Must have own understanding to this piece! The direction of learning is to fill gaps, one step at a time to eat! If you eat a whole piece, you’ll find it boring! You may not need it in development, but interviewing is one of the most important areas to master!

The data structure

1. How many kinds of data structure storage are commonly used? What are their characteristics?

Data storage structure is an important content of data structure. In a computer, the storage structure of data can be represented in four ways.

  • Sequential storage

Simply put, sequential storage means storing data one after another in a contiguous storage area. In the sequential storage mode, logically connected nodes are stored in adjacent storage units in physical locations, and the logical relationship between nodes is reflected by the adjacency of storage units. Sequentialstorage, also known as sequentialstorage structure, is generally described by array or structural array. Linear storage is mainly used for data storage of linear logical structure, but not for nonlinear logical structure such as graph and tree.

  • Link storage

The link storage method is flexible, which does not require that logically adjacent nodes be physically adjacent, and the logical relationship between nodes is represented by additional reference fields. The reference field of one node usually indicates the location of the next node. LinkedStorage is also called LinkedStorage Structure. Generally, application types are added to the original data items to represent the location relationship between nodes.

  • Index storage

Index storage is a storage method that uses additional index tables to store node information. An index table consists of several index entries. The general format of index items in index storage mode is :(keyword, address). A keyword is a data item that uniquely identifies a node.

  • Index storage can also be divided into the following two categories:

    • Dense Index: A Dense Index in which each node has an Index entry in the Index table. The address of the index item indicates the storage location of the node.

    • Spare Index: A set of nodes that correspond to only one Index entry in the Index table. Where, the address of the index item indicates the starting storage location of a group of nodes.

  • Hash storage mode

Hash storage is a storage method that directly calculates the storage address of a node according to its keywords. In practical applications, it is often necessary to decide which storage mode to adopt according to the specific data structure. Different storage structures can be obtained by using different storage methods for the same logical structure. These four methods can be used alone or combined to describe data structures.

Set structure Linear structure tree structure graph structure unidirectional linked list bidirectional linked list circular linked list 4. 5. Stacks, stacks, and queues

  • Common iOS algorithms and data structures
  • Preliminary Study on data StructureThere’s a lot of data structures in there, and you can go through more on your own

6. Enter the root of a binary tree and find the depth of the tree.

If a tree has only one node, its depth is 1. If the root has only left subtrees and no right subtrees, then the depth of the tree should be the depth of the left subtree plus 1. Similarly, if the root has only right subtrees and no left subtrees, then the depth of the tree should be the depth of the right subtree plus 1. If you have both right and left subtrees, the depth of the tree is the greater value of the depth of the left and right subtrees plus one.

public static int treeDepth(BinaryTreeNode root) {
    if (root == null) {
        return 0;
    }
    int left = treeDepth(root.left);
    int right = treeDepth(root.right);
    return left > right ? (left + 1) : (right + 1);
}
Copy the code

7. Input the root node of the binary tree in lesson 1 and determine whether the tree is a balanced binary tree.

  • (1) The solution requiring repeated traversal of nodes for several times
  • (2) the solution of traversing each node only once
  • Reference article:

algorithm

1. Time complexity

In computer science, time complexity, also known as time complexity, is a function that qualitatively describes the running time of an algorithm. This is a function that represents the length of the string input to the algorithm. The time complexity is often expressed in large O notation, excluding the lower order and leading coefficients of the function. In this way, the time complexity can be said to be asymptotic, that is, as the size of the input approaches infinity. Temporal complexity

2. Space complexity

Space Complexity is a measure of the amount of storage Space temporarily occupied by an algorithm while it is running, denoted by S(n)=O(f(n)). For example, the time complexity of direct insertion sort is O(n^2), and the space complexity is O(1). A normal recursive algorithm would have order n space complexity, because every time you recurse, you have to store the information that comes back. The merits and demerits of an algorithm are mainly measured from the execution time and storage space of the algorithm. Time complexity & space complexity

3. Common sorting algorithms

  • 1. Bubble sort
  • 2. Selection sort
  • 3. Insert sort
  • 4. Hill sort
  • 5. Quicksort
  • Merge sort
  • Heap sort
  • 7 common sorting algorithms

4. String reversal

- (NSString *)reversalString:(NSString *)originString{
    NSString *resultStr = @ "";
    for (NSInteger i = originString.length - 1; i >= 0; i--) {
      NSString *indexStr = [originString substringWithRange:NSMakeRange(i, 1)];
      resultStr = [resultStr stringByAppendingString:indexStr];
    }
  return resultStr;
}
Copy the code

5. List inversion (head difference method)

public Node reverseList(a){
        Node cur = head;
        Node prev = null;
        Node curNext = head.next;
        Node reverHead = null;
        while(cur! =null){
            cur.next = prev;
            cur = curNext;
            prev = cur;
            curNext = curNext.next;
        }
        reverHead = cur;
        return reverHead;
}

> 6. Ordered array merge objc - (void)merge {
    /* Ordered array A: 1, 4, 5, 8, 10... 1000000, ordered array B: 2, 3, 6, 7, 9... 999998, the two arrays A and B do not repeat each other, please merge into an ordered array C, write the code and time complexity. * /
    / / (1).
    NSMutableArray *A = [NSMutableArray arrayWithObjects:@4The @5The @8The @10The @15, nil];
// NSMutableArray *B = [NSMutableArray arrayWithObjects:@2,@6,@7,@9,@11,@17,@18, nil];
    NSMutableArray *B = [NSMutableArray arrayWithObjects:@2The @6The @7The @9The @11The @12The @13, nil];
    NSMutableArray *C = [NSMutableArray array];
    int count = (int)A.count+(int)B.count;
    int index = 0;
    for (int i = 0; i < count; i++) {
        if (A[0]<B[0]) {
            [C addObject:A[0]];
            [A removeObject:A[0]];
        }
        else if (B[0]<A[0]) {
            [C addObject:B[0]];
            [B removeObject:B[0]];
        }
        if (A.count==0) {
            [C addObjectsFromArray:B];
            NSLog(@"C = %@",C);
            index = i+1;
            NSLog(@"index = %d",index);
            return;
        }
        else if (B.count==0) {
            [C addObjectsFromArray:A];
            NSLog(@"C = %@",C);
            index = i+1;
            NSLog(@"index = %d",index);
            return; }}/ / (2).
    // Time complexity
    //T(n) = O(f(n)): "T(n)", "O" is a mathematical symbol, f(n) is the same order of magnitude, generally is the algorithm of the largest frequency statement frequency.
    // Time complexity :T(n) = O(index);
}
Copy the code

7. Find the first character that appears only once (Hash lookup)

Two ideas:

  • 1:hash� Different compilers handle character data differently, so the character type is converted to an unsigned type before hash.
  • 2. Space for time, withBuffer arrayRecords characters that are currently found only once, avoiding double traversal.
# define SIZE 256
char GetChar(char str[])
{
  if(! str)return 0;
  char* p = NULL;
  unsigned count[SIZE] = {0};
  char buffer[SIZE];
  char* q = buffer;
  for(p=str; *p! =0; p++)
  {
    if(++count[(unsigned char)*p] == 1)
      *q++ = *p;
  }
  
  for (p=buffer; p<q; p++)
  {
    if(count[(unsigned char)*p] == 1)
    return *p;
  }
return 0;
}
Copy the code

8. Find the common parent of the two child views

Suppose the two views are UIViewA and UIViewC, where UIViewA inherits from UIViewB and UIViewB inherits from UIViewD. UIViewC also inherits from UIViewD; Namely – A – > B > D, C – > D

- (void)viewDidLoad {
    [super viewDidLoad];
    Class commonClass1 = [self commonClass1:[ViewA class] andClass:[ViewC class]].NSLog(@ "% @",commonClass1);
    // Output: 2018-03-22 17:36:01.868966+0800 The nearest public parent of two UIViews [84288:2458900] ViewD
}
// Get all the parent classes
- (NSArray *)superClasses:(Class)class {
    if (class= =nil) {
        return@ []; }NSMutableArray *result = [NSMutableArray array];
    while (class! =nil) {
        [result addObject:class];
        class = [class superclass];
    }
    return [result copy];
}

- (Class)commonClass1:(Class)classA andClass:(Class)classB {
    NSArray *arr1 = [self superClasses:classA];
    NSArray *arr2 = [self superClasses:classB];
    for (NSUInteger i = 0; i < arr1.count; ++i) {
        Class targetClass = arr1[i];
        for (NSUInteger j = 0; j < arr2.count; ++j) {
            if (targetClass == arr2[j]) {
                returntargetClass; }}}return nil;
}
Copy the code
  • Method 1 is obviously a two-layer for loop with time complexity ofO(N^2)An improved approach: We put all points in a path into an NSSet first. Because the internal implementation of an NSSet is a hash table, the time complexity of querying elements becomesO(1), we have a total of N nodes, so the total time complexity is optimizedO(N)
- (Class)commonClass2:(Class)classA andClass:(Class)classB{
    NSArray *arr1 = [self superClasses:classA];
    NSArray *arr2 = [self superClasses:classB];
    NSSet *set = [NSSet setWithArray:arr2];
    for (NSUInteger i =0; i<arr1.count; ++i) {
        Class targetClass = arr1[i];
        if ([set containsObject:targetClass]) {
            returntargetClass; }}return nil;
}
Copy the code

9. The median in an unordered array (quick sorting idea)

Reference: Find the median in an unordered array

10. Given an array of integers and a target value, find two numbers that neutralize the target value in the array.

You can assume that there is only one answer for each input and that the same elements cannot be reused. Example: Given nums = [2, 7, 11, 15], target = 9 —

  • The first level for loop takes each element from index 0 to the penultimate index,
  • The second for loop iterates through the elements that follow the previous for loop.
  • Refer to the article
class Solution {
    public int[] twoSum(int[] nums, int target) {
       int len = nums.length;
        int[] result = new int[2];
        for(int i = 0; i < len; i++){
            for(int j = i+1; j < len; j++){
                if(nums[i] + nums[j] == target){
                    result[0] = i;
                    result[1] = j; 
                    returnresult; }}}returnresult; }}Copy the code

Analysis: This module is the Achilles heel of most developers! This module is the best test of a candidate’s thinking skills! But I don’t recommend asking candidates to hand-write data structures or algorithmcode in a stressful interview environment. It can be challenging! Thinking to I feel almost!

Architecture design

1: What problems are design patterns designed to solve?

Design pattern is a set of repeatedly used, most people know, cataloged code Design experience summary. Design patterns are used to re-use code, make it easier for others to understand, and ensure code reliability.

The main problem that design patterns solve is to deal with software changes by encapsulating and isolating change points. The benefit of isolating change is that isolating frequently changing parts of the system from stable parts helps increase reusability and reduce system coupling. Many design patterns clearly point to a solution to a problem in their intent, and the point of learning a design pattern is to discover the points of change encapsulated in their solution.

Three classic books: GOF Design Patterns, Analysis of Design Patterns, Head First Design Pattern

Design patterns are one of the essence of software development. Learning design patterns well is now a required course for every developer,

2. Which third-party frameworks have you read and how are they designed?

This topic sees your individual feeling, consider your at ordinary times skill foundation! You can target some common frameworks: RxSwift, Alamofire, Moya, AFNetworing, YYKit…. Master will use at the same time, must master the bottom of the core ideas!

3: What are some refactoring tips? When do you think refactoring should be done?

  • Refinement of repetitive code
  • Verbose method segmentation
  • Optimization of nested conditional branches
  • Remove one-time temporary variables
  • Eliminate long parameter lists
  • Extract constants from a class or inheritance system
  • Make the class provide the methods it should
  • Break up long classes
  • Extract repeated properties and methods from the inheritance system to the parent class

When new features are added, when extensions are no longer simple. Refactoring is a continuous process.

4. How do you select common architectural design patterns in development?

This is also an open question! It doesn’t mean that one architecture is the best — only the most suitable! According to the situation of the company, the status of the project, and the level of developers timely adjustment, design!

5: How do you decouple components?

The most commonly used mode of iOS decoupling and componentalization is unified hop routing. Currently, the commonly used iOS open source routing frameworks are JLRoutes, MGJRouter, HHRouter, etc. These routing frameworks have their own advantages and disadvantages and can basically meet most requirements. At present, it is most commonly used as a route jump to realize basic component-based development and decoupling between modules. However, in practical development, it will be found that they cannot be completely used to complete all inter-module communication, such as synchronous and asynchronous communication between modules. For example, after configuring the URL of the relevant route hop, how to dynamically modify the relevant hop logic after going online? How to dynamically modify related parameters when modules are communicating with each other? Can APP realize 302 jump similar to Web? To study the reference

Analysis: Architecture design this layer for an iOS senior developer. That’s the one he has to think and feel about! If the candidate has been developing application-layer interfaces for four or five years, he’s probably already behind in his future career advancement! The interviewer may wish to design a separate part of this module to discuss with the candidate. After all, these thoughts may be designed to bring something different to the interviewer! 😊

Performance optimization

1: What is a good performance optimization scheme for tableView?

2. How do you deal with interface lag and detection?

3: What is your understanding of off-screen rendering?

4: How to reduce the size of APP package

5. How to check for memory leaks?

6. What aspects should be optimized for APP startup time?

  • IOS_tableView performance optimization
  • IOS version interface caton monitoring scheme
  • IOS understanding of off-screen rendering and solutions
  • How does iOS reduce the size of apps
  • IOS memory leak detection method
  • Optimization analysis of iOS app startup time

Analysis: Now APP performance optimization has become a must for iOS advanced developers! I personally suggest that you communicate with job seekers based on actual development. Rather than just stay in the knowledge point question and answer, because there is no actual ability to develop performance optimization is just an empty promise!

conclusion

This set of interview questions still has certain level and difficulty! But to apply for an iOS senior development position, or more pertinent! I hope you can have your own ideas in the next job hopping.

The article has long, the suggestion pays attention to the backup, whether is interviewing or is about to interview, should be helpful to you! Since you see this: please give it a thumbs up! 👍

PS: There are questions on the content of this article also hope to point out, thank you! Come on, look forward to your good news