(iOS Interview Guide)

1. Introduce the NSURLConnection class and + sendSynchronousRequest: returningResponse: error: with – initWithRequest: delegate: what is the difference between two methods?

A: NSURLConnection is mainly used for network access, including + sendSynchronousRequest: returningResponse: error: access to the data is synchronized, namely, the current thread blocks, and wait for the request to return the response, And – initWithRequest: delegate: using the asynchronous loading, when its complete network access, by the delegate to return to the main thread, and the delegate object.

2. When to select GCD and NSOperation in the project

A: The advantage of using NSOperation in a project is that NSOperation is a high abstraction of threads. Using NSOperation in a project will make the program structure of the project better. The design idea of subclassing NSOperation has the advantages of object-oriented (reuse, encapsulation), which makes the implementation support multi-threading, and the interface is simple. Recommended for complex projects.

The advantage of using GCD in a project is that GCD itself is very simple and easy to use. For non-complex multi-threaded operations, it will save the amount of code, and the use of Block parameter will make the code more readable, so it is recommended to use it in a simple project.

3. How does the ViewController didReceiveMemoryWarning get called

A: [supper didReceiveMemoryWarning];

4. Write a setter method for @Property (nonatomic, retain) NSString *name
- (void)setName:(NSString *)str{
    [str retain];
    [_name release];
    _name = str;
}
- (void)setName:(NSString *)str{
    id t = [str copy];
    [_name release];
    _name = t;
}
Copy the code
5. For the NSString *obj = [[NSData alloc] init]; What type of object does obj have at compile time and at run time?

A: The type is NSString at compile time; The runtime is an object of type NSData

6. What is the method of creating a thread in Object C? If the code is executed in the main thread, what is the method? If you want to delay the execution of the code, what method?

A: There are three ways to create a thread: using NSThread, using GCD’s Dispatch, subclassing NSOperation, and then adding it to NSOperationQueue; In the main thread to execute code, the method is performSelectorOnMainThread, if you want to delay implementation code can use the performSelector: onThread: withObject: waitUntilDone:

7. What’s the difference between shallow replication and deep replication?

A: Shallow replication: only Pointers to objects are copied, not the reference objects themselves.

Deep replication: copies the reference object itself.

8. PerformSelecter

When calling NSObject performSelecter: afterDelay: after its internal will actually create a Timer and add to the current thread RunLoop. So if the current thread does not have a RunLoop, then this method will fail.

When the performSelector: onThread: when, in fact, it will create a Timer is added to the corresponding thread, in the same way, if the corresponding thread no RunLoop this method will fail.

9. What aspects of optimization do you work on?

First, the home page start speed

Do as little as possible during startup (merge as many interfaces as possible)

Do not perform time-consuming operations on the UI thread (data processing is carried out in the child thread, processing is completed notify the main thread to refresh the program) start background tasks at the appropriate time (for example, in the user guide program can start to prepare the data to load) Jsonkit, SBJson) data paging (if there is more back-end data, it should be returned in pages, such as netease News, or Microblog records) data compression (big data can also be compressed back, reduce traffic, speed up response) content cache (for example, the latest news list of netease News should be cached to the local and loaded from the local, Can be cached in memory, or database, depending on the situation) delayed TAB loading (for example, if an app has 5 tabs, you can load the first TAB to be displayed first, and the others can be loaded at display time, as needed)

Optimization of the algorithm (optimization of the core algorithm, for example, some apps have a contact name sorted with the first letter of Chinese pinyin)

Three, operation smoothness optimization Tableview optimization (Tableview Cell load optimization) ViewController load optimization (jump between different views, Can be prepared in advance data) four, the optimization of the database database design above the query statement reconstruction of the optimization of the database table (too much data, Can divide five different tables or libraries), the server side and client interactions Request the client to minimize the service side try to do more logic to handle the server and the client to push-pull combination of (can use some synchronization mechanism) communication protocol optimization (reduce the size of the message) power usage optimization (try not to use the background) 6, non-technical performance optimization of product design logic (product design must be logical, or logic as simple as possible, otherwise it will make programmers crazy, sometimes it takes a lot of effort to complete a small logical design problem) interface interaction specification (interface interaction of each module as unified as possible, Code specification (this can lead to stealthily improved app performance, such as using if else or switch, or using! Code review continues to refactor code. Reduces the logical complexity of the code)

10. What is the difference between using the weak keyword and assigning?

1. In ARC, when a circular reference is possible, it is often resolved by having one end use weak, such as the delegate property.

2. If you have made a strong reference to it once, you do not need to make a strong reference again. In this case, weak is also used. Of course, you can also use strong. Why can an IBOutlet view attribute be set to Weak? A: Because the parent control’s subViews array already has a strong reference to it. The differentia assign can be used for non-OC objects, while Weak must be used for OC objects. Weak indicates that the property defines a “non-ownership relationship.” Property values are automatically cleared (nil) when the object to which the property refers is destroyed.

11. NSString/NSArray/NSDictionary declared with @property often uses the copy keyword. Why? What problems might arise if you use the strong keyword instead?

A: NSString, NSArray, and NSDictionary often use the copy keyword because they have variable types: NSMutableString, NSMutableArray, and NSMutableDictionary may assign between them (that is, assign mutable to immutable). To ensure that the string value in an object does not unintentionally change, a copy should be made when setting the value of a new property.

1. Since the pointer of the parent class can point to the object of the subclass, the purpose of using copy is to make the property of the object not affected by the outside world. No matter whether the object passed by copy is mutable or immutable, I myself hold an immutable copy. 2. If we use strong, it is possible for this property to refer to a mutable object. If the mutable object is modified externally, this property will be affected. Summary: The purpose of using copy is to prevent the mutable type object from inadvertently tamper with the original value of the immutable type object when the mutable type object is assigned to an immutable type object.

12. How can Runtime set weak to nil?

Runtime lays out the registered classes and places the Weak object in a hash table. When the object’s reference count is zero, the object’s dealloc method is called. If the object’s memory address is a, a search is made for the weak hash table with a as the key. Find all weak objects with key A and set them to nil

13. What is a runloop?

Runloop is part of the thread-dependent infrastructure. A runloop is an event-handling loop that continuously schedules work and processes input events. Inside is a do-while loop that continuously processes various tasks (such as Source, Timer, Observer). The purpose of using Runloop is to keep your threads busy when they are working and dormant when they are not.

14. UITableViewCell has a UILabel that displays the NSTimer implementation stopwatch time. Does the label refresh when scrolling the cell?

Whether this is refreshed depends on what Mode the timer adds to the Run Loop. Mode specifies the priority of the event in the loop

  • NSDefaultRunLoopMode (kCFRunLoopDefaultMode) : Default, idle
  • UITrackingRunLoopMode: This Mode is switched when ScrollView slides
  • UIInitializationRunLoopMode: run loop starts, will switch to this mode
  • NSRunLoopCommonModes (kCFRunLoopCommonModes) : Mode collection

Apple publicly offers two modes

  • NSDefaultRunLoopMode (kCFRunLoopDefaultMode)
  • NSRunLoopCommonModes (kCFRunLoopCommonModes)

In programming: If we add an NSTimer object to the main run loop with NSDefaultRunLoopMode (kCFRunLoopDefaultMode), the mode switch during ScrollView will cause the NSTimer to no longer be scheduled. When we scroll and want to be unscheduled, we should use the default mode. However, if you want the timer to be called back while scrolling, you should use common mode.

15. Is NStimer accurate? What do you think? If not, how do you implement an accurate NSTimer?

Is not allowed; The reasons are as follows

1. NSTimer is added to the main Runloop, and the mode is NSDefaultRunLoopMode. Main is responsible for all main thread events, such as UI interface operations and complex operations, so that timer will block in the same Runloop. 2. Mode change. There are two preset modes in the RunLoop of the main thread: kCFRunLoopDefaultMode and UITrackingRunLoopMode. When you create a Timer and add it to DefaultMode, the Timer will get repeated callbacks, but when you slide a ScrollView, RunLoop will switch mode to TrackingRunLoopMode, and the Timer will not be called back. It also doesn’t affect the slide operation. So that affects the NSTimer error. PS:DefaultMode is the normal state of the App, and rackingRunLoopMode is the state of tracking ScrollView sliding. Method: 1. Perform the NSTimer operation on the main thread, but add the instance of NSTimer to the specific mode of the main Runloop. Timer = [NSTimer timerWithTimeInterval:1 target:self Selector :@selector(showTime) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; 2, in the child thread NSTimer operation, -(void)timerMethod2 {NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil]; [thread start]; NewThread {@ autoreleasepool {} – (void) [NSTimer scheduledTimerWithTimeInterval: 1.0 target: the self selector:@selector(showTime) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] run]; }}

16. What are the advantages of NSOperation compared with GCD?

GCD is a low-level API based on C, and NSOperation belongs to the object-c class. Ios first introduced NSOperation, IOS4 later introduced GCD and NSOperationQueue and it was implemented internally using GCD.

Compared to GCD: 1, NSOperation has more functions available, see the API for details. 2. In the NSOperationQueue, you can set up dependencies between nsOperations.

3, kvo can monitor whether the operation isExecuted (isFinished), whether to cancel (isCanceld).

4. NSOperationQueue can conveniently manage the priority of concurrent nsOperations. GCD is mainly used in combination with block. The code is concise and efficient. GCD can also achieve complex multi-threaded applications, mainly to establish a dependency on each thread time such cases, but the need to implement their own than NSOperation is more complex. Which one to use depends on your needs. From a personal point of view, the best way to use it is to use the GCD as much as possible except for dependencies, because Apple has specifically optimized the performance of the GCD.

17. How to access and modify the private properties of a class?

There are two ways to access private properties, either through KVC or through Runtime to access and modify private properties.

18. How do I catch exceptions?
1. In the app starts (didFinishLaunchingWithOptions), add an exception handling surveillance NSSetUncaughtExceptionHandler (& UncaughtExceptionHandler); Void UncaughtExceptionHandler(NSException *exception){// Obtain NSArray *excpArr = [exception] callStackSymbols]; NSString *reason = [exception reason]; NSString *name = [exception name]; NSString *excpCnt = [NSString stringWithFormat:@"exceptionType: %@ \n reason: %@ \n stackSymbols: %@",name,reason,excpArr]; / / daily log storage (this function can be separate refining to a method) NSArray * dirArr = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory NSUserDomainMask, YES); NSString *dirPath = dirArr[0]; NSString *logDir = [dirPath stringByAppendingString:@"/CrashLog"]; BOOL isExistLogDir = YES; NSFileManager *fileManager = [NSFileManager defaultManager]; if (! [fileManager fileExistsAtPath:logDir]) { isExistLogDir = [fileManager createDirectoryAtPath:logDir withIntermediateDirectories:YES attributes:nil error:nil]; } if (isExistLogDir) {// NSString *logPath = [logDir stringByAppendingString:@"/ crashlog.txt "]; [excpCnt writeToFile:logPath atomically:YES encoding:NSUTF8StringEncoding error:nil]; }}Copy the code
19. Can object-c classes inherit multiple times? Can multiple interfaces be implemented? What is Category? Is it better to override a class by inheritance or by classification? Why is that?

A: Object-c classes cannot be inherited multiple times. Can implement multiple interfaces, through the implementation of multiple interfaces can complete the C++ multiple inheritance; A Category is a Category. In general, you can use a Category to override a class. It only works for this Category, and it doesn’t affect the relationship between the other classes and the original class.

20. The difference between Category, Extension and inheritance

Answer: 1. Classification

In principle, a category can only add new methods to an existing class (the only reason it can add properties is because runtime solves the problem of having no setter/getter). The compiler does not have any warning if a method in a class is not implemented, because the category is added to the class at runtime. Extension in iOS is an anonymous category, only the header file has no implementation file. Class extension method can not only increase, but also can increase the instance variable (or properties), only the instance variable is @ private by default (use only in their own class, rather than a subclass or elsewhere), declared in a class extension method is not implemented, the compiler will report to the police, this is because the class extension is 3 in the compile phase was added to the class. Inheritance In iOS inheritance is single inheritance, so there can only be one parent class. In inheritance, a subclass can use methods and variables of its parent class. When a subclass wants to initialize a variable of its parent class or class, it needs to override the init() method. A parent class can also access methods and member variables of a child class

21. Describe memory partitions

1). Code area: Store function binary code

2). Data area: Memory is allocated and initialized when the system is running, and released by the system when the system exits. 3). Heap area: dynamically obtained by functions such as malloc or operators such as new, requiring the programmer to manually apply and release 4). Stack: applied in function module, which is automatically released by the system when the function ends. Store local variables, function parameters

22. What happens when you call the _objc_msgForward function directly?

_objc_msgForward is IMP type for message forwarding: when a message is sent to an object, but it is not implemented, _objc_msgForward tries to do message forwarding.

Calling _objc_msgForward is a very dangerous thing to do. If you don’t use it well, it will Crash your program, but if you use it well, you can do a lot of really cool things. If you call _objc_msgForward, you will skip IMP lookup and trigger “message forward”. If you call _objc_msgForward, you will tell objc_msgSend even if the object actually implements this method: “I don’t find an implementation of this method in this object.”

23. Understanding of Run Loop
  • RunLoop is a magic weapon for multithreading, that is, a thread can only perform one task at a time, after the completion of the task will exit the thread. The main thread will continue to wait for the receiving event without exiting after executing the immediate task. The nonprimary thread is usually designed to perform a task and then return the resource, so by default it does not run RunLoop.
  • Each thread has its own RunLoop, but only the RunLoop of the main thread is started by default, and the RunLoop of other sub-threads is not started by default. To start the RunLoop, you need to manually start it.
  • In a separate thread, you need to enable RunLoop if you want to continue to receive events without exiting after processing a task.
  • NSRunLoop provides a method to add an NSTimer. You can specify Mode. If you want to call back in all cases, you need to set Mode to Common.
  • Essentially, there is no runloop for child threads by default because Apple uses lazy loading. If we had not called [NSRunLoop currentRunLoop] manually, we would not have queried whether the current thread’s RunLoop existed, nor would we have loaded it, nor created it.
24. How does Runtime find the IMP address by selector? (Consider class methods and instance methods, respectively)

1. An object method list for each class object (object method cache)

The class method list is stored in the metaclass object that isa pointer points to in the class object (class method cache) 3. Each method structure in the method list records the name of the method, the method implementation, and the type of the arguments. In fact, the selector is essentially the method name, which is used to find the corresponding method implementation in the method list. When we send a message to an NSObject, the message looks for 5 in the object’s class object method list. When we send a message to a Class, the message is looked up in the list of methods on the Class’s Meta Class object

25. The difference between SEL and IMP in Runtime

Method name SEL – indicates the name of the method;

IMP – a function pointer to the implementation of the method.

26. Underlying implementation of block

A block is essentially a pointer to a structure

A more advanced feature of the runtime mechanism is that the OC code written in pure C is converted into the C runtime code instructions: clang-rewrite-objc main.m(which can be printed and verified) By default, any block is on the stack and can be recycled at any time As soon as you copy it once the memory of the block is in the heap and it’s not going to be freed and you have to copy to create a new memory address and all the addresses change

27. TCP three-way handshake

The TCP protocol uses the three-way handshake policy. After sending a packet using TCP protocol, TCP will not ignore the situation after the transmission, it will confirm to the other party whether the delivery was successful. The TCP flags SYN(Synchronize) and ACK(acknowledgement) are used in the handshake. The sender first sends a packet with the SYN flag. After receiving the packet, the receiver sends back a packet with SYN/ACK flag to convey the acknowledgement. Finally, the sender sends back a packet with an ACK flag, indicating the end of the handshake.

28. What is the nature of @property?

@property = ivar + getter + setter;

There are two concepts of property: ivar (instance variable) and getter+setter (access method).

29. The underlying implementation of KVC?

When an object calls the setValue method, the method internally does the following:

1). Check if there is a set method for the corresponding key, and if so, call the set method. 2). If the set method does not exist, it looks for the underlined member variable with the same name as key, and if it does, it assigns a value directly to the member variable attribute. 3). If _key is not found, the attribute key of the same name will be looked up, if there is a value directly assigned. 4). If you haven’t found, the call to valueForUndefinedKey: and setValue: forUndefinedKey: method. The default implementation of these methods is to throw exceptions, and we can override them as needed.

30. ViewController lifecycle

In order of execution:

1). InitWithCoder: triggered when initializing through a NIB file. 2). AwakeFromNib: When the nib file is loaded, an awakeFromNib message will be sent to each object in the niB file. 3). LoadView: Starts loading the view controller’s built-in view. 4). ViewDidLoad: The view controller’s view is loaded. 5). ViewWillAppear: The view controller’s view will be displayed on the window. 6).updateViewConstraints: The View controller’s view starts updating the AutoLayout constraint. 7).viewwillLayOutSubViews: The position where the view controller’s view will update the content view. 8). ViewDidLayoutSubviews: The view controller’s view has updated the position of the view. 9). ViewDidAppear: The view controller’s view is already displayed on the window. 10). ViewWillDisappear: View controller’s view is about to disappear from window 11). ViewDidDisappear: View controller’s view has disappeared from window

31. How to synchronize several asynchronous calls with GCD? (for example, load multiple images asynchronously according to several urls, and then synthesize a whole image after downloading)
// Append blocks to the Global Group Queue using the Dispatch Group. If all of these blocks are completed, the terminating blocks in the Main Dispatch Queue will be executed. Dispatch_group_t group = dispatch_group_create(); Dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); Dispatch_group_async (group, queue, ^{/* load image 1 */}); Dispatch_group_async (group, queue, ^{/* load image 2 */}); Dispatch_group_async (group, queue, ^{/* load image 3 */}); // Execute the following code: dispatch_group_notify(group, dispatch_get_main_queue(), ^{// merge images});Copy the code
32. What is the function of dispatch_barrier_async?
Function definition: dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block); Functions: 1. It is executed after the preceding task is finished, and the following task is executed after it is finished. Dispatch_queue_t queue = dispatch_queuE_CREATE ("myQueue", DISPATCH_QUEUE_CONCURRENT); Dispatch_async (queue, ^{// 1.2 is parallel NSLog(@" task 1, %@",[NSThread currentThread]); }); Dispatch_async (queue, ^{NSLog(@" task 2, %@",[NSThread currentThread]); }); Dispatch_barrier_async (queue, ^{NSLog(@" task barrier, %@", [NSThread currentThread]); }); Dispatch_async (queue, ^{// these two are simultaneous NSLog(@" task 3, %@",[NSThread currentThread]); }); Dispatch_async (queue, ^{NSLog(@" task 4, %@",[NSThread currentThread]); }); // Task 1, task 2, task 3, task 4.Copy the code