1. Briefly introduce the NSURLConnection class and+ sendSynchronousRequest:returningResponse:error:with- 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 *nameWrite 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

5. For statementsNSString *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?

Do as little as possible during the startup process (merge multiple interfaces as much as possible) do not make time-consuming operations on the UI thread (data processing in the child thread, After processing, notify the main thread to refresh the program.) Start background tasks at an appropriate time (for example, you can start preparing loaded data in the user guide program). An SBJson) data paging (backend data, more is paging to return, such as netease news, or microblog records) data compression (big data can be compressed to return, reduce the flow, speed up the reaction) content caching (such as netease news list of the latest news is to cache to local, from the local load, can be cached in memory, Or database, depending on the situation) delayed TAB loading (for example, the APP has 5 tabs, the first TAB to be displayed can be loaded first, others can be loaded at the time of display, as needed) algorithm optimization (optimization of the core algorithm, For example, some apps have a contact name sorted by the first letter of The Chinese pinyin. Can prepare data in advance) four, the optimization of the database database design above the reconstruction of the query optimization sub-database sub-table (when the data is too much, 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) 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. Different points 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. The property value is automatically cleared (nil) when the object to which the property refers is destroyed.

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?

The Runtime 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) : Mode set Apple provides two modes publicly
  • NSDefaultRunLoopMode (kCFRunLoopDefaultMode)
  • NSRunLoopCommonModes (kCFRunLoopCommonModes) 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; 1. NSTimer is added to 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, execute NSTimer operation in child thread, -(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, 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. NSOperation has more functions available than GCD. For details, see the API. 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 * is extensible herelogPath = [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: In principle, a category can only add new methods to an existing class (attributes can only be added because the Runtime solves the problem of not having a setter/getter). The compiler does not warn that methods in the category are not implemented, because the category is added to the class at runtime. Extension in iOS 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 3 in the compile phase was added to the class. Inheritance 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

2). Data area: memory is applied and initialized when the system is running, and released by the system when the system exits. Storage of global variables, static variables, constants 3). Heap area: through malloc and other functions or operators such as new dynamic application, programmers need to manually apply and release 4). Stack area: function module application, the end of the function by the system automatically released. 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)

Each class object has a list of object methods (object method cache). 2. The list of class methods is stored in the metaclass object to which the ISA pointer points (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. When we send a message to an NSObject object, the message looks 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. So by default, any block is on 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 all the addresses change

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: Check if there is a set method for the corresponding key, and call the set method if there is. 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

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, ^{// These are simultaneous NSlogs (@)"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

Attached: my blog address