This article mainly introduces the iOS interview questions, interested partners can refer to it

1. Briefly introduce the NSURLConnection class and+ sendSynchronousRequest:returningResponse:error:And –initWithRequest:delegate:The difference between the 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 do you choose to use GCD and NSOperation in the project

A: The advantage of using NSOperation in the project is that NSOperation is highly abstract to threads. Using NSOperation in the project will make the program structure of the project better. The design idea of subclassing NSOperation has the advantages of object-oriented (reuse and encapsulation), making the implementation supported by multi-threading and the interface 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 uncomplicated multi-threaded operations, it will save the amount of code, while the use of Block parameter will make the code more readable, so it is recommended to use it in simple projects.

3. ViewController didReceiveMemoryWarning is called

A: [supper didReceiveMemoryWarning];

4. Write a setter method for completion@property(nonatomic, retain) NSString *name,Write a setter method to do this@property(nonatomic, copy) 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
NSString *obj = [[NSData alloc] init]; What type of object is obj at compile time and at run time?

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

6. What is the method of creating threads in Object C? If you execute code in the main thread, what is the method? What are the methods if you want to delay code execution?

A: There are three ways to create a thread: use NSThread creation, use GCD dispatch, use subclassed NSOperation, and then add 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 is the difference between shallow and deep replication?

A: Shallow copy: copies only Pointers to objects, not reference objects themselves.

Deep copy: 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, 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. Where do you start to optimize?

First, the home page startup speed

Do as little as possible during startup (merge as many interfaces as possible). Do no time-consuming operations on the UI thread (data is processed in the child thread, and the main thread is notified to refresh the program after processing). Start background tasks at appropriate times (for example, you can start preparing loaded data in the user guide program).

2. Page browsing speed JSON processing (iOS comes with NSJSONSerialization, Jsonkit, SBJson) data paging (if there is a lot of back-end data, it will be returned paging, such as netease news, or Microblog records) data compression (big data can also be returned compression, reduce traffic, Content cache (for example, the latest news list of netease News should be cached locally, which can be cached to memory or database, depending on the situation) delayed TAB loading (for example, if the APP has 5 tabs, the first TAB to be displayed can be loaded first, and others can be loaded at display time. Optimization of algorithm (optimization of core algorithm, for example, some apps have a contact name sorted by the first letter of Chinese pinyin)

Three, operation fluency optimization Tableview optimization (Tableview cell loading optimization) ViewController loading optimization (jump between different views, you can prepare data in advance)

Four, the optimization of the database database design above the reconstruction of the optimization of the query statement sub-database sub-table (too much data, can be divided into different tables or libraries)

Five, server and client interaction optimization client to minimize the request server to do as much as possible logical processing server and client to take the combination of push and pull (can use some synchronization mechanism) communication protocol optimization (reduce the size of the message) electricity use optimization (try not to use background operation)

Six, non-technical performance optimization of product design logic (product design must be logical, or logic as simple as possible, otherwise it will make programmers mad, sometimes with a lot of effort, can complete a small logic design problem) interface interaction specification (each module interface interaction as far as possible unified, Code specification (this can be used to improve app performance, such as if else or switch, or use! Keep refactoring your code. Reduce logical complexity of code)

10. What is the difference between the weak keyword and assign?

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

2. It has been strongly referenced once by itself, so there is no need to strongly reference it again. In this case, weak is also used. Of course, you can also use strong. Why can the view property connected by IBOutlet be set to weak?

A: Because the parent control’s subViews array already has a strong reference to it.

Differences: Assign can be used with non-OC objects, while weak must be used with OC objects. Weak indicates that the property defines a non-ownership relationship. Property values are automatically cleared when the object to which the property refers is destroyed (nil)

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

NSString, NSArray, and NSDictionary often use copy because they have mutable types: NSMutableString, NSMutableArray, and NSMutableDictionary, which may perform assignment operations among themselves (that is, assigning mutable values to immutable ones), should be copied when setting new property values to ensure that string values in the object do not change unintentionally. 1. Because a parent class pointer can point to a subclass object, the purpose of using copy is to make the properties of this object unaffected by the outside world. Using copy, whether it is passed to me as a mutable object or an immutable object, I hold an immutable copy. 2. If we use strong, the property may point to a mutable object, and if the mutable object is modified externally, the property will be affected.

Summary: The purpose of using copy is to prevent the assignment of a mutable object to an immutable object from inadvertently tampering with the original value of the immutable object.

12. How does runtime automatically set weak variables to nil?

Untime lays out the registered classes and puts the weak object into a hash table. When the reference count of this object is 0, the dealloc method will be called. If the memory address of the object pointed to by weak is A, the dealloc method will be searched in the hash table with a as key. Find all weak objects with key A and set them to nil

13. What is runloop?

Runloop is part of the thread-specific infrastructure. A runloop is an event processing loop that continuously dispatches 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 thread busy when it is working and dormant when it is not.

14. There is a UILabel on the UITableViewCell, which displays the stopwatch time implemented by NSTimer.

Whether this is refreshed or not depends on what Mode the timer adds to the Run Loop. Mode is mainly used to specify the priority of events in the run cycle, divided into

  • NSDefaultRunLoopMode (kCFRunLoopDefaultMode) : the default, idle state
  • UITrackingRunLoopMode: This Mode is switched when ScrollView slides
  • UIInitializationRunLoopMode: run loop starts, will switch to this mode
  • NSRunLoopCommonModes (kCFRunLoopCommonModes) : Set of modes

Apple has two publicly available modes

  • NSDefaultRunLoopMode (kCFRunLoopDefaultMode)
  • NSRunLoopCommonModes (kCFRunLoopCommonModes)

In programming: If we add an NSTimer object to the main running loop as NSDefaultRunLoopMode (kCFRunLoopDefaultMode), during the ScrollView, the NSTimer will no longer be scheduled because of the mode switch. When we scroll, we want to not schedule, so we should use the default mode. However, if you want the timer to be called back when scrolling, you should use Common Mode

15. Is NStimer accurate? What’s your opinion? How do you implement an accurate NSTimer if not?

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 in the same runloop timer will block. 2. Model change. The main RunLoop has two preset modes: kCFRunLoopDefaultMode and UITrackingRunLoopMode. When you create a Timer and add DefaultMode, the Timer will get repeated callback, but when you swipe a ScrollView, RunLoop will switch mode to TrackingRunLoopMode, and the Timer will not be called back. And it doesn’t affect the sliding operation. So it’s going to affect NSTimer errors. PS:DefaultMode is the normal state of App, and rackingRunLoopMode is tracking the state of ScrollView when sliding.

1. Do the NSTimer operation on the main thread, but add the NSTimer instance to the specific mode of the main runloop. Self. timer = [NSTimer timerWithTimeInterval:1 Target :self selector:@selector(showTime) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; 2. Perform the NSTimer operation in the child thread, and then modify the UI interface in the main thread to display the operation result

-(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]; }}Copy the code
16. What are the advantages of NSOperation compared with GCD?

GCD is a low-level API based on C, NSOperation belongs to object-C class. NSOperation was first introduced in ios, then GCD and NSOperationQueue were introduced in ios 4 and internally implemented in GCD. Relative to GCD:

NSOperation has more functions available. See the API for details.

2. In NSOperationQueue, dependencies between nsOperations can be established.

3. Kvo monitors whether an operation isExecuted, finished, or cancelled.

4. NSOperationQueue can easily manage priorities between concurrent and NSOperations. GCD is mainly used in conjunction with blocks. The code is simple and efficient.

GCD can also implement complex multi-threaded applications, mainly to establish the time dependence of each thread such as the situation, but the need to implement itself is more complex than NSOperation. Which one to use depends on your needs. From a personal point of view, it is more appropriate to use GCD except for dependencies, because Apple has specifically optimized performance for GCD.

17. How do I access and modify private attributes of a class?

There are two ways to access private properties, either through KVC or through the 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); 2. Capture and save exception logs locally 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 be multiple inherited? Can you implement multiple interfaces? What’s a Category? Is it better to rewrite a class by inheritance or by classification? Why is that?

A: Object-c classes cannot be multiple inherited; Can realize multiple interfaces, through the realization of multiple interfaces can complete C++ multiple inheritance; Category is a Category. In general, the method of using Category to rewrite a class is only effective for this Category and does not affect the relationship between other classes and the original class.

20. The difference between Category, Extension and inheritance

A:

1. In principle, you can only add new methods to an existing class (attributes can be added only because the Runtime solves the problem of not having a setter/getter). The compiler does not warn if methods in a category are not implemented, because the category is added to the class at runtime

In iOS, extension is an anonymous category, with only the header file and 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 the compile phase is added to the class

Inheritance in iOS is single inheritance, which means there can only be one parent class. In inheritance, a subclass can use its parent’s methods and variables. When a subclass wants to initialize its own class or its parent’s variables, it overrides the init() method. The parent class also has access to the methods and member variables of the subclass

21. Describe memory partitions

1). Code area: store binary codes of functions

2). Data area: memory is applied and initialized when the system is running, and released by the system when the system exits. Store global variables, static variables, and constants

3). Heap area: it can be dynamically applied by functions such as malloc or operators such as new, and it needs to be manually applied and released by programmers

4). Stack area: applied in function module, released by the system automatically at the end of the function. Store local variables, function parameters

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

_objc_msgForward is an IMP type for message forwarding: when a message is sent to an object and it is not implemented, _objc_msgForward will attempt to forward the message. Calling _objc_msgForward directly is a very dangerous thing to do and will Crash the program if used badly, but it can do a lot of cool things if used well. Once _objc_msgForward is called, it skips the IMP lookup process and triggers “message forwarding” directly. If _objc_msgForward is called, you’ll 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, the magic weapon of multithreading, means that a thread can execute only one task at a time, and then exit the thread. The main thread continues to wait for events to be received after completing an instant task without exiting. The non-main thread is usually used to perform a task, and the resource needs to be returned upon completion, so RunLoop is not run by default; Each thread has its own RunLoop, but only the main thread RunLoop is started by default, the other child thread RunLoop is not started by default, to start manually. In a separate thread, you need to enable RunLoop if you want to wait for events to be received without exiting after processing a task. NSRunLoop provides a method to add NSTimer. You can specify Mode. If you want to call back in any case, you need to set Mode to Common Mode. Essentially, runloops for child threads do not exist by default, because Apple uses lazy loading. If we had not manually called [NSRunLoop currentRunLoop], we would not have queried the current thread’s RunLoop, loaded it, and created it.

24. How does runtime find the corresponding IMP address by selector? (Consider class and instance methods respectively)

1. Each class object has a list of object methods (object method cache)

2. 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, method implementation, and parameter type. In fact, selector is essentially the name of the method, through which the corresponding method implementation can be found in the method list.

4. When we send a message to an NSObject object, the message is looked up in the object’s class object method list

5. When we send a message to a Class, the message will be looked up in the list of methods in 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 a concrete implementation of the method, which IMP is.

26. Block underlying implementation

A block is a pointer to a structure. A block is a pointer to a structure. A block is a pointer to a structure By default, any block is in the stack, it can be reclaimed at any time and once you copy it once the memory of the block is in the heap and it’s never released and only copy can create a new memory address and everything changes

27. TCP three-way handshake

TCP uses the three-way handshake. After sending a packet using TCP, TCP does not ignore the situation after transmission. It must confirm whether the packet was successfully delivered to the other party. TCP tokens SYN(Synchronize) and ACK(Acknowledgement) are used during the handshake. The sender first sends a packet with the SYN flag to the peer. After receiving the packet, the receiving end sends a packet with the SYN/ACK flag to confirm the packet. 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;

Property has two main concepts: IVAR (instance variable) and getter+setter (access method).

29. The underlying implementation of KVC?

When an object calls the setValue method, the following operations are done inside the method:

1). Check whether there is a corresponding key set method, if there is, call set method.

2). If the set method does not exist, it looks for an underlined member variable with the same name as key, and if it does, it assigns the value directly to the member variable attribute.

3). If _key is not found, the attribute key of the same name will be looked for, 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 initialized by niB file.

2).awakeFromNib: When the NIB file is loaded, an awakeFromNib message is sent to each object in the NIB file.

3). LoadView: Starts loading the view that comes with the view controller.

4). ViewDidLoad: The view of the view controller is loaded.

5). ViewWillAppear: View controller’s view will be displayed on the window.

6). UpdateViewConstraints: The view of the view controller starts updating the AutoLayout constraint.

7). ViewWillLayoutSubviews: The view controller’s view will update the position of the content view.

ViewDidLayoutSubviews: The view controller’s view has updated the position of the view.

9). ViewDidAppear: The view controller’s view is displayed on the window.

10). ViewWillDisappear: The view controller’s view will disappear from the window.

11). ViewDidDisappear: A view controller’s view disappears from the window.

31. How to synchronize several asynchronous calls with GCD? (For example, load multiple images asynchronously based on several urls, and then compose a whole image after downloading them all)
// Use the Dispatch Group to append blocks to the Global Group Queue. If all of these blocks are executed, the end-of-processing block 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 picture 1 */}); Dispatch_group_async (group, queue, ^{/* load picture 2 */}); Dispatch_group_async (group, queue, ^{/* load picture 3 */}); // Group_notify (group, dispatch_get_main_queue(), ^{// merge image});Copy the code
32. What does dispatch_barrier_async do?
Function definitions: dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block); Functions: 1. It is executed after the preceding tasks are completed, and the following tasks are executed after the preceding tasks are completed. Dispatch_queue_t queue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT); // add 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, ^{NSLog(@" task 3, %@",[NSThread currentThread])); }); Dispatch_async (queue, ^{NSLog(@" task 4, %@",[NSThread currentThread]); }); // Task 1 and task 2, task 3 and task 4 are processed in parallel in uncertain order.Copy the code

The above is all the content of this article, I hope to help you

The original address