👏 Visit my GitHub for more content. Click to go to GitHub
In the summer of 2019, the weather in Chengdu was extremely hot and muggy.
Because of the cause of the company, cause I have to consider to interview a large stable and mature company, has been from the start dream of entering a company can get a broad platform development, one day can become the technical director, but the reality is always cruel, for four years, four years, each time the interview will feel or just answer: I know, but I haven’t looked into it. I’ve read about it, but I haven’t dealt with it yet. Then is a strong sweating to relieve the pressure of the heart. Changed jobs 3 times, interviewed 30-40 times, each time just for interview (memorized), a lot of things do not remember. Oh, I’m so hard. I’m so hard
Whether you pass the interview or not, let’s summarize some of the most common interview questions.
Summary of the object-C series of interview questions
Basic questions:
1. Inheritance, classification, extension
A Category B Extension C Inheritance D Inheritance
A: 1. The classification has a name, but the class extension does not have a name. It is a special classification. 2. Classification can only extend methods (attribute is only a statement is not true, because in the run-time, the object's memory layout have been confirmed, if you add an instance variable will destroy the internal layout of a class, it is disastrous for a compiled language), typically used to declare a private method, extension or private property, private member variables. 3. Inheritance can add, modify, or delete methods, and can add attributes.Copy the code
So: Three features of a class (encapsulation, inheritance, polymorphism)
Description of the Category and Extension principles in iOS
IOS member variables/instance variables/property variables
2. Can objective-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 not override a class’s original method in a category?
A: Objective-C class can not have multiple inheritance, OC is all single inheritance, multiple inheritance can be simulated using protocol delegate implementation can implement multiple interfaces, you can achieve multiple inheritance by implementing multiple interfaces OC Category is class; ⚠️ Is it better to override a class by inheritance or classification: is it better to override a class by inheritance or classification? It depends. Suppose the target class has many subclasses. We need to extend this class without affecting the existing code. After inheritance is better. If you just extend the method. Classification is better. (no need to involve the original code) Methods in a class take precedence over methods in the original class. That is, methods in the class override methods in the original class ⚠️ Why not override methods in a class in a category: 1. There is no way for a category to replace a subclass. It cannot call a method of the superclass through super like a subclass. If a class overrides a method in the current class, then the original method implementation in the current class will never be executed, which is fatal in some methods. (ps: By the way, the +(void)load method is a special case that executes in a category after the current class has executed.) 2. Also, a category cannot reliably override the same methods of the same class in another category. For example, UIViewController+A and UIViewController+B, both overwrite viewDidLoad, so we can't control who overwrites who. 3. Looking at the header files, we can see that many classes in the Cocoa framework use categories to implement their functions, and you may inadvertently override one of these methods, sometimes resulting in undetectable exceptions. 4. Categories were created to make it easier for developers to extend a class. They are not intended to make you change a class. Conclusion: To override methods, of course, we can override methods of the parent class by subclass. In some inconvenient cases, we can also do method swizzling using Runtime in the category.Copy the code
3. What is polymorphism? What is classification? What is an agreement?
A: In object-oriented languages, polymorphism means that the same interface can be implemented in different ways. In OC, polymorphism means that different objects respond to the same message in different ways. A child class changes the implementation of the same method by overriding the method of the parent class. In general terms, polymorphism means that a pointer to a parent type points to an object in a subclass. When a function (method) is called, it can call the correct version of the function (method). Polymorphism is the multiple forms of something. Inheritance is a prerequisite for polymorphism;Copy the code
A: Classification: Without modifying the original class code, you can add the Categroy method to the class extension method, or associate attributes, The underlying structure of Categroy is also a structure: internally stores the name of the structure, the classification of that class, a list of objects and class methods, protocols, and property information. The combined Category data (methods, attributes, protocols) is inserted in front of the original data of the class at the beginning of the compiled Category data after merging into a large arrayCopy the code
A: Protocol: a protocol is a set of standards that declare a number of methods, but do not care how they are implemented. The implementation is done by the classes that follow the protocol. In OC, a class can implement multiple protocols, through the protocol can make up for the defects of single inheritance, but the protocol is not the same as inheritance, the protocol is just a list of methods, method implementation depends on the class to follow this protocol to implement.Copy the code
4. Please explain and compare the following keywords: strong, weak, assign, copy.
A: * strong refers to and owns the object. The reference count of the object it decorates increases by 1. The object will not be destroyed as long as the reference count is not zero. And of course you can destroy it by forcing it to nil. Weak refers to but does not own the object. The reference count of the object decorated by it does not increase. No manual setting is required. The object is automatically destroyed in memory. * Assign is used primarily to modify basic data types, such as NSInteger and CGFloat, that exist primarily on the stack. Weak is usually used with objects and assign is usually used with basic data types. The reason is that after the assign object is released, the address of the pointer still exists, resulting in wild pointer and easy to crash on the heap. The memory on the stack will be handled automatically and will not cause wild Pointers. * Copy is similar to strong. The difference is that while strong copies multiple Pointers to the same address, copy copies the object one at a time with Pointers to different addresses in memory. Copy is usually used to describe immutable objects with mutable corresponding types, such as NSString, NSArray, NSDictionary. * In Objective-C, the default keys for basic data types are atomic, readWrite, assign; The default keywords for normal properties are atomic, readwrite, strong.Copy the code
5. NSString/NSArray/NSDictionary declared with @property often uses 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. // Copy is used to prevent unintentionally tamper with the original value of an immutable object if the mutable object is assigned to an immutable object.Copy the code
Understanding depth copy in iOS – Why does NSString use copy
6. What’s the difference between a shallow copy and a deep copy?
A: Shallow copy: only the pointer to the object is copied, not the reference object itself. Deep copy: Copies the reference object itself. There are two separate copies of the object itself in memory. When you change A, A_copy does not change.Copy the code
A deep copy of iOS
7. How is memory management in Objective-C? What is your opinion and solution?
A: There are three main ways to manage memory in Objective-C: ARC(automatic memory count), manual memory count, and memory pool. 1). Automatic memory counting ARC: Xcode automatically adds memory management code to the code during App compilation. 2). Manual memory count MRC: follow the memory who apply, who release; He who adds, he who releases. 3). Release Pool: Put all the memory to be released into one Pool. When the Pool is drained, all the memory space in the Pool will be released automatically. A memory pool can be released automatically or manually. Automatic release is affected by the Runloop mechanism.Copy the code
8. What do we mean when we say OC is dynamic runtime language?
Answer: It mainly postpones data type determination from compile time to run time. In simple terms, the runtime mechanism allows us to not determine the class of an object and call the methods specified for that class object until run time.Copy the code
9. What are KVO and KVC? What about KVC and KVO?
A: KEY-value-coding (KVC) is an indirect way to access instance variables. Provides a mechanism for indirectly accessing the properties of an object. 1. Assign values to private variables. 2. Assign values to internal attributes of the control (such as custom UITextFiled clearButton, or placeholder color). Ivar * Ivar = class_getInstanceVariable Gets an instance member variable. [textField setValue:[UIColor redColor] forKeyPath:@"placeholderLabel.textColor"]; 3, combined with the Runtime, model conversion and dictionary (setValuesForKeysWithDictionary, class_copyIvarList for Ivar member list) of the specified class is a kind of based on KVC KVO implement the observer pattern. KVO notifying observers, either automatically or manually, when the properties of the specified observed object have changed. Example: Listen to the contentOffSet property of ScrollView [ScrollView addObserver:self forKeyPath:@" contentOffSet "] options:NSKeyValueObservingOptionNew context:nil];Copy the code
KVO figure
10. Block
A: 1. In the case of using an external pointer inside a block and causing a circular reference, we need to use __weak to modify the external pointer: __weak Typeof (self) weakSelf = self; 2. If the delay function is called inside the block and the weak pointer is used, the pointer will not be retrieved because it has been destroyed. You need to re-reference the weak pointer inside the block. __strong typeof(self) strongSelf = weakSelf; 3. If you need to change an external stack variable inside a block, you need to use __block to modify the external stack variable.Copy the code
Heap, stack, and queue
A: 1. In terms of management mode, the stack is automatically managed by the compiler without manual control. In the case of the heap, freeing work is controlled by the programmer, leading to memory leaks. 3. From the perspective of data storage, stack space is generally stored in the basic type, the address of the object heap space is generally stored in the object itself, block copy, etcCopy the code
A heap is a sorted tree data structure, where each node has a value. Usually we refer to the data structure of the heap as a binary tree. So the heap in the data structure can usually be thought of as an array of objects in a tree. And the heap needs to satisfy two properties: 1) the value of a node in the heap is always no greater than or less than the value of its parent node; 2) The heap is always a complete binary tree. There are two kinds of heaps. There is a maximum heap and a minimum heap. The root node of the largest heap is called the maximum heap or large root heap, the root node of the smallest heap is called the minimum heap or small root heap, in a set of elements in the minimum heap, the elements of the parent node must be smaller than the elements of the child node, but for the size of the left and right nodes is not specified who is big and who is small. Heap are commonly used to implement a priority queue, access to heap is random, it's like we of the bookshelf in the library book, although the book put is sequential, but we want to take any one don't have to be like a stack, first take out in front of all the books, bookshelves this mechanism is different from the box, we can directly take out we want to book. A stack is a linear table that is restricted to inserting and deleting only at the end of the table. We call the top of the stack the end that allows insertions and deletions, the bottom of the stack the end that does not contain any data elements, the empty stack. The special thing about the stack is that it restricts the insertion and deletion of this linear table, which is always at the top of the stack. Stack is a Last In First Out (LIFO) data structure, also known as Last In First Out (LIFO) linear table. That is to say, we take what is stored first, and we take what is stored first. This is similar to the way we take something at the bottom of the box (something put in earlier), we first have to remove something that is pressing on it (something put in later). There are operations defined in the stack. The two most important ones are PUSH and POP. The PUSH operation adds an element to the top of the stack. The POP operation, by contrast, removes an element at the top of the stack and reduces the size of the stack by one. A queue is a linear table that allows inserts at one end and deletes at the other. The end that allows insertion is called the end of the queue, and the end that allows deletion is called the head of the queue. It is a special kind of linear table. What makes it special is that it allows only deletes at the front end of the table and inserts at the back end of the table. Like a stack, a queue is a linear table with limited operations. Queue is a first-in, first-out (FIFO) data structure, also known as first-in, first-out (FIFO) linear table. This means that what goes in first comes out, and what goes in later comes out later. It's like when you go through security, the luggage that goes in first comes out first at the other end, and the luggage that goes in later comes out at the back.Copy the code
12. What is the relationship between UIView and CALayer?
A: UIView inherits from UIResponder, and UIResponder is a responder object that can respond to and pass events in iOS. The CALayer does not inherit from UIResponder, so the CALayer does not have the ability to respond to and handle events. A CALayer is a class in QuartzCore, which is a low-level class used to draw content. It is used to draw UI. UIView encapsulates properties of the CALayer. UIView encapsulates the CALayer, which makes it easy to set the position of the control; Properties such as rounded corners, shadows, etc., UIView is not further encapsulated, so we still need to set the Layer properties to implement the function. UIView is a proxy for a CALayer. UIView holds a property of the CALayer and is a proxy for that property to provide data for some of the CALayer's rows, such as animation and drawing.Copy the code
How do JS and OC call each other?
A: There are three ways for JS to call OC: Method 1: replace function(method) in JS; method 2: inject objects and directly call object method; method 3: use web page redirection and intercept strings; oc calls JS code in two ways 1. Through the webVIew call webVIew stringByEvaluatingJavaScriptFromString: call 2. EvaluateScript :];Copy the code
14. How to understand HTTP? / What’s the difference between Http and Https? Why IS Https more secure?
A: HTTP is essentially a Protocol. Its full name is Hypertext Transfer Protocol. HTTP is a TCP/ IP-based communication protocol to transfer data. The protocol is used to specify the rules of transmission between the client and the server. The content to be transmitted is not limited to text (in fact, any type of data can be transmitted). An HTTP can be regarded as a transaction, and its working process is divided into four steps: 1. The client establishes a connection with the server 2. After the connection is established, the client sends a request to the server. 3. After receiving the message, the server responds with Operation 4. After receiving the message, the client displays the message on the screen and disconnects the client.Copy the code
A: Differences 1. You need to apply for a CA certificate for HTTPS, which is rarely free. 2.HTTP is transmitted in plaintext, while HTTPS is encrypted based on SSL. 3. The HTTP port number is 80 and the HTTPS port number is 443. 4.HTTPS is encrypted transmission with authentication, which is more secure. Secure SSL(Secure Socket Layer) TLS(Transport layer security) Above the transport layer, network connections are encrypted to ensure data integrity and enhance security.Copy the code
15. The Six Design Principles of Programming?
A: 1. The single responsibility principle generally means that a class does only one thing, CALayer: animation and view display. UIView: only responsible for event passing and event response. 2. Open and Close Principle: Open for modification but open for extension. 3. Interface isolation principle Use multiple specialized protocols rather than one bloated one, such as UITableviewDelegate + UITableViewDataSource 4. The principle of dependency inversion Abstractions should not depend on concrete implementations. Concrete implementations can depend on abstractions. A parent class can be replaced seamlessly by a subclass, and the original function is not affected. For example: KVO 6. Demeter's Law an object should know as little about other objects as possible, achieving high aggregation and low couplingCopy the code
17. What is the sandbox directory structure? For which scenarios?
Documents: Common directories, iCloud backup directories, data Library Caches: stores large data that do not need to be backed up Preference: Settings directory, iCloud backs up Settings TMP: Temporary files that will not be backed up, and the data in this file can be erased at any timeCopy the code
17. What are the data persistence schemes in iOS?
A: SQLite CoreData SQLite CoreData SQLite CoreData It provides object-relational mapping (ORM) capabilities that convert OC objects to data stored in SQLite database files and restore data stored in the database to OC objects, managing the application's data model through CoreData)Copy the code
18. The lifecycle of a single viewController?
-initWithcoder :(NSCoder *)aDecoder :(if storyboard or xib is used) -loadView: load view-viewDidLoad: Load view-viewwillAppear: The controller's view will be displayed - viewWillLayoutSubviews: The controller's view will be laid out with child controls - viewDidLayoutSubviews: Controller's view layout child controls complete - viewDidAppear: controller's view is fully displayed - viewWillDisappear: Controller's view is about to disappear - viewDidDisappear: Controller's view completely disappears when - dealloc controller is destroyedCopy the code
19. What is Cocoa and Cocoa Touch? / Cocoa Touch Underlying technology Architecture?
A: Cocoa contains the Foundation and AppKit frameworks for developing applications for Mac OS X. Cocoa Touch contains the Foundation and UIKit frameworks for developing applications for the iPhone OS. Cocoa is the development environment for Mac OS X, and Cocoa Touch is the development environment for iPhone OS.Copy the code
Cocoa Touch: UI components, touch events and event-driven, system interface Media layer: Audio and video playback, animation,2D and 3D graphics Core Server: Core OS: Memory management, underlying network, disk managementCopy the code
20. How do I select delegate, Notification, and KVO?
Answer: In all three modes, one object passes events to another and does not want them to be coupled. Delegate. One-to-one Notification one-to-many, many-to-many KVO one-to-one have their own characteristics: The Delegate syntax is simple, easy to read, and easy to debug. Notification is flexible, and can be implemented across multiple classes using KVO for property listening, and model and View synchronization can be implemented in different ways depending on the scenarios encountered in actual developmentCopy the code
21. Have you ever played Instrument in normal development?
A: There are many tools in Instruments. The common ones are: (1).Time Profiler: Performance Profiler. You can see that the various methods in the application are consuming CPU time. (2).zoombies: Checks if zombie objects were accessed, but this tool can only check from top to bottom, not smart (3).allocations: Checks memory and the people who wrote the algorithm use this also (4).Leaks: Check memory for memory leaks (5).Core Animation: Evaluate graphics performance. This option checks whether the image is scaled and whether the pixels are aligned. Images that have been scaled up are marked yellow, and pixels that are misaligned are marked purple. The more yellow and purple, the worse the performance.Copy the code
Common sorting algorithm
Answer: The selection sort, bubble sort, and insertion sort algorithms can be summarized as follows: They all divide the array into sorted and unsorted parts. Select sort defines the sorted part on the left, and then selects the smallest element of the unsorted part to be swapped with the first element of the unsorted part. Bubble sort defines the sorted part at the right end and performs an exchange during the process of traversing the unsorted part, swapping the largest element to the right end. Insertion sort defines the sorted part on the left and inserts the first element of the unsorted part into the appropriate place for the sorted part. / * * * "selection" : the most value in between * * trip 1: in the n number found in (large) number of minimum 2 trips to swap places with the first number * : in the remaining find the minimum number n - 1 (large) number of swap places with the second number * repeat operation... The third, the fourth... The number exchange position * n-1 trip, finally can realize the ascending (descending) order of data. * */ void selectSort(int *arr, int length) { for (int i = 0; i < length - 1; For (int j = I + 1; j < length; J++) {/ / times if comparing (arr [I] > arr [j]) {int temp = arr [I]; arr[i] = arr[j]; arr[j] = temp; }}}} /** * [Bubble sort] : Compare the two adjacent elements in pairs, after the comparison, the most value appears at the end * the first time: compare the two adjacent numbers in turn, constantly swap (before the decimal, after the large number put) advance one by one, the most value finally appears at the NTH element position * the second time: Compare the two adjacent numbers in turn, constantly switching (before the decimal number, after the large number) advance one by one, the most value finally appears in the n-1 element position *...... ... */ void bublleSort(int *arr, int length) {for(int I = 0; i < length - 1; For (int j = 0; int j = 0; j < length - i - 1; J++) {/ / times if comparing (arr [j] > arr [j + 1]) {int temp = arr [j]; arr[j] = arr[j+1]; arr[j+1] = temp; }}}} /** * Split search: Optimize the search time (without traversing all the data) ** The principle of split search: * 1> Array must be ordered * 2> Must know min and Max (know range) * 3> Dynamically calculate mid and fetch mid for comparison * 4> If mid is greater than the value we are looking for, So Max is going to be smaller than mid-1 * 5> if mid is less than the value we're looking for, Int int (int *arr, int length, int key) {int min = 0, int (int *arr, int length, int key) {int min = 0, max = length - 1, mid; while (min <= max) { mid = (min + max) / 2; If (key > arr[mid]) {min = mid + 1; } else if (key < arr[mid]) { max = mid - 1; } else { return mid; } } return -1; }Copy the code
SDWebImage Image loading process
Differences between iOS memory cache and disk cache
Cache is divided into memory cache and disk cache two kinds, the memory refers to the current program running space, cache speed is small capacity, is temporary storage of files, for the CPU directly read, such as open a program, he is stored in the memory, close the program memory will return to the original free space; Disk is the storage space of the program, the cache capacity is large, the speed is slow and persistent. Unlike memory, disk is the permanent storage of things, as long as there is something stored in it, no matter whether it is running or not, it takes up space! The disk cache is located in the Library/Caches.
1. Look for the cache corresponding to the image in WebImagecache. It takes the URL as the data index and first looks for whether there is a cache in the memory; 2. If there is no cache, it searches for the corresponding data in the disk through the KEY processed by MD5. If found, the data in the disk will be added to the memory and displayed. 3. If it is not found in memory or disk, it will send a request to the remote server and start downloading the image. 4. Add the downloaded images to the cache and write them to the disk; 5. The whole process of obtaining pictures is carried out in the child thread and displayed in the main thread.Copy the code
Analysis of UNDERLYING principles of AFNetworking
A: AFNetworking is a encapsulated NSURLSession network request consisting of five modules: By NSURLSession respectively, Security, Reachability, Serialization, UIKit NSURLSession five parts: Network communication module (core module) corresponds to AFNetworking AFURLSessionManager and specialized processing of the HTTP protocol AFHTTPSessionManager AFHTTPSessionManager is inherited in AFURLSessionManager Security: Network communication security policy module corresponding AFSecurityPolicy Reachability: network status monitoring module corresponding AFNetworkReachabilityManager Seriaalization: Network communication information serialization and deserialization module corresponding AFURLResponseSerialization UIKit: for iOS UIKit extension librariesCopy the code
Advanced:
1. The underlying implementation of KVC?
A: When an object calls setValue, 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.Copy the code
2. The underlying implementation of KVO?
When you add KVO to class A, runtime dynamically generates A subclass NSKVONotifying_A, makes the isa pointer to class A point to NSKVONotifying_A, overwrites the class method, and conceals the actual class information of the object. Override the setter method for the listening property, Inside the setter method calls the Foundation _NSSetObjectValueAndNotify function 3. Call willChangeValueForKey _NSSetObjectValueAndNotify function within a) first B) then assign a value to the property c) finally call the didChangeValueForKey d) finally call the observer's observeValueForKeyPath to tell the listener that the property value has changed. 4. Rewrite dealloc to do some KVO memory freeCopy the code
3. How do you optimize performance at work
Answer: is generally said about the optimization of tableView processing, cause tableView card reason 1. The reuse identifier of the cell is not used, resulting in the creation of new cells 2. The relayout of the cell 3. The properties and contents of the cell are not calculated and cached in advance. 4. Too many controls in the cell 5. 6. Update only tableView.reloadData() (if only updating a group, use reloadSection for partial updates) 7. 8. AddView 9 dynamically to the cell using addView. Cells are not loaded on demand (when the cell scrolls quickly, only the cells within the range are loaded) 10. Implement useless proxy methods (tableView only adheres to two protocols) 11. EstimatedHeightForRow cannot exist at the same time as the layoutIfNeed in HeightForRow. The suggestion is: write the estimated line height whenever the line height is fixed to reduce the number of line height calls and improve performance. If it is a dynamic line height, do not write the estimation method. Instead, use a cache dictionary of the line height to reduce the number of calls to the code. When drawRect: is implemented, its rect parameter is the region to be drawn, and anything outside this region does not need to be drawn. No pre-rendered images. (There is still a brief pause when new images appear. The solution is to draw it in the Bitmap context first, export it into UIImage objects, and then draw it to the screen) to improve the smoothness of the tableView * is essentially to reduce the CPU, GPU work, from these two big aspects to improve performance. CPU: object creation and destruction, object attribute adjustment, layout calculation, text calculation and typesetting, image format conversion and decoding, image rendering 2.GPU: Texture rendering card optimization at the CPU level 1. Try to use lightweight objects, such as CALayer instead of UIView 2 where event handling is not needed. Do not frequently call UIView properties such as frame, bounds, and Transform to minimize unnecessary changes 3. Calculate the layout as much as possible in advance, and adjust the corresponding properties once as needed. Do not modify the properties multiple times. 4. The size of the image should be exactly the same as the size of the UIImageView 6. Control the maximum number of concurrent threads 7. Try to place time-consuming operations on child thread 8. Text processing (size calculation, drawing) 9. Image processing (decoding, drawing) lag optimization at the GPU level 1. 2. The maximum texture size that GPU can process is 4096x4096. Once it exceeds this size, CPU resources will be occupied for processing, so the texture should not exceed this size 3. 4. Reduce the number of transparent views (alpha<1) and set opaque to YES 5. Try to avoid off-screen renderingsCopy the code
Tips for keeping the interface flowing on iOS
5. What is the Runtime implementation mechanism? What can be done?
A: Runtime is short for runtime. OC is the runtime mechanism, which means that some processing is done at runtime. For example, C knows which method function to call at compile time, while OC does not know which method function to call at compile time, and only knows the name of the method function to call at run time, so as to find the corresponding method function to call. 1. Send messages [scenario: method invocation] 2. Exchange method implementation (exchange system method) [Scenario: When the third-party framework or system native method function can not meet our needs, we can keep the system's original method function, on the basis of adding additional functions. 3. Dynamic adding methods [Scenario: If there are too many methods in a class, it takes more resources to load the class into memory, and you need to generate a mapping table for each method. You can use dynamic adding methods to a class to solve this problem.] 4. Add attributes to a category using an AssociatedObject. [Scenario: You cannot customize attributes and variables for a category, so you can use Runtime to dynamically add attributes. Declaring an attribute on a class is essentially adding an association to the class, not directly adding the value's memory space to the class storage space. 1.NSCoding automatic archive unfile scenario: If a model has more than one property, implementing a custom model data persistence method would require you to implement encodeObject and decodeObjectForKey for each property. Use the functions provided by Runtime to traverse all the attributes of the Model itself, and conduct encode and decode operations on the attributes. Use Runtime to traverse all attributes in the model, look up the key in the dictionary according to the attribute name of the model, take out the corresponding value, and assign values to the attributes of the model. Use the message forwarding mechanism to solve the exception problem that cannot be found by the methodCopy the code
Teach you a deep understanding of Runtime mechanics
The use of Runtime at work
Runtime Mechanism
6. IOS image Settings with rounded corners have performance problems
A: Use setCornerRadius [this will trigger an off-screen render, which is performance consuming. For example, when a page has more than a dozen heads on it, the rounded corners will appear to be too tight. PNG UIImageView with rounded corners will not render off screen. ShouldRasterize = YES rasterizer 【 avatarImageView. Layer. ShouldRasterize = YES; AvatarImageViewUrl. Layer. RasterizationScale = [UIScreen mainScreen]. Scale; / / UIImageView without it will produce a little fuzzy ShouldRasterize =YES sets rasterize to enable off-screen render results to be cached in memory as a bitmap. This saves the performance of off-screen render if the layer and sublayers are changed frequently. It will always render and delete caches and re-create caches, so it is not recommended to use rasterization in this case, which is also a performance loss. 4. Use UIImage drawInRect to draw rounded corners [This method consumes less GPU and consumes more memory, and UIButton does not know how to draw, You can use UIimageView to add a tap gesture and use it as a UIButton. 5. Core Graphics draws rounded corners when SDWebImage is processed (temporary feeling is the best method)Copy the code
IOS image Settings with rounded corners performance issues
7. What is a RunLoop?
A: It's literally a running loop, and inside it is a do-while loop, in which tasks are continuously processed. A thread corresponds to a RunLoop, which basically keeps the program running and handles various events in the app. With Runloop, you can save CPU resources and improve performance by running while you need to. The run loop for the main thread is started by default. In the iOS app, Int main(int argc, char * argv[]) {@autoreleasepool {return UIApplicationMain(argc, argv, nil, argv) NSStringFromClass([AppDelegate class])); }}Copy the code
A: RunLoop is a magic weapon for multithreading, that is, a thread can only execute 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.Copy the code
In-depth understanding of RunLoop iOS Multithreading: a detailed summary of “RunLoop”
8. Triggered by scheduledTimerWithTimeInterval timer, when sliding on the page list, the timer will be suspended, why? How to solve it?
Answer: The reason is that the current thread's Runloop switches mode for list sliding, causing the timer to pause. The mode in runloop is used to specify the priority of events in runloop. The modes are as follows: * Default (NSDefaultRunLoopMode) : Default. * Connection (NSConnectionReplyMode) : This is used by systems to process nsConnection-related events, but not by developers; * Modal (NSModalPanelRunLoopMode) : handles Modal Panels event; * Event Tracking (NSEventTrackingRunLoopMode) : used for processing drag and user interaction patterns. * Common (NSRunloopCommonModes) : a collection of modes. The Default modes include Default, Modal and Event Tracking, which can handle almost all events. Let's go back to the situation. When sliding the list, the mode of the Runloop is switched from the original Default mode to the Event Tracking mode. The timer was running well in the Default mode, and naturally stopped working after being closed. One solution is to add a timer to NSRunloopCommonModes. The second is to place the timer in another thread and then start the runloop of the other thread, so that it does not interfere with the main thread, which is currently handling the page slide.Copy the code
Method 1 [[NSRunLoop currentRunLoop] addTimer: timer forMode: NSRunLoopCommonModes]; Method 2 dispatch_async(dispatch_get_global_queue(0, 0), ^{ timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(repeat:) userInfo:nil repeats:true]; [[NSRunLoop currentRunLoop] run]; });Copy the code
9. Processes and threads
A: process: 1. Process is a program with certain independent functions about a data set of a run activity, it is the basic unit of the operating system to allocate resources 2. Process refers to an application running in the system, which is the execution process of a program. We can understand it as an APP. 3 on the mobile phone. Each process is independent of each other, each process runs in its own dedicated and protected memory space, and has all the resource threads needed to run independently 1. 2. A process must have at least one thread in order to execute tasks. When an application is started, the system starts a thread by default, which is the relationship between the main thread and the thread 1. A thread is the execution unit of a process. All tasks of a process are executed in a thread. 2. A program can correspond to multiple processes (multiple processes), a process can have multiple threads, but at least one thread 4. Threads within the same process share process resourcesCopy the code
10. What are the characteristics of several solutions to realize multithreading in iOS? What are the specific usage scenarios/when to choose GCD and NSOperation in a project?
A: Pthread is a set of universal multi-threaded API, which can be used in Unix/Linux/Windows and other systems. Written in C language, programmers need to manage the life cycle of threads by themselves, which is difficult to use. We hardly use PThread in iOS development. But still can come to understand. NSThread is object oriented and requires the programmer to manually create threads, but does not require manual destruction. Communication between child threads is difficult. GCD C language, take full advantage of the device's multiple cores, automatically manage the thread life cycle. It's more efficient than NSOperation. NSOperation is based on GCD encapsulation, more object oriented, more functionality than GCD. [Scenario: 1. Perform the next step after multiple network requests are completed. 2. Perform the next step after multiple network requests are executed in sequence.Copy the code
A: The advantage of using NSOperation in a project is that NSOperation is highly abstract to the thread. Using NSOperation in a project will make the program structure of the project better. The design idea of subclassing NSOperation is that it has the advantages of being image oriented (reuse, encapsulation), which makes the implementation multi-threaded support. The interface is simple and 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 operation, 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.Copy the code
IOS multithreading: detailed summary of pthread and NSThread iOS multithreading: detailed summary of GCD iOS multithreading: detailed summary of NSOperation and NSOperationQueue
11. What is the COMMUNIST Party? What is the queue type of GCD?
A: Grand Central Dispatch (GCD), also called Grand Central Dispatch (GCD), encapsulates the thread operation, adds many new features, internal efficiency optimization, provides a concise C language interface, more efficient use, is also recommended by Apple. There are two types of queues in GCD: 1. Concurrent Dispatch Queue allows multiple tasks to be executed concurrently (automatically enable multiple threads to execute tasks simultaneously). A Serial Dispatch Queue allows tasks to be executed one after the other, in FIFO order.Copy the code
12. What are synchronous and asynchronous task dispatch?
A: Multiple threads in GCD often use dispatch_sync and dispatch_async functions to add tasks to the specified queue, which are synchronous and asynchronous, respectively. Synchronous: Blocks the current thread until the added time-consuming task Block is completed, then the function returns, and then the subsequent code can continue to perform asynchronous: After a task is added to the queue, the function returns immediately. The following code does not have to wait for the completion of the added task to execute. Asynchronous submission cannot determine the order of task executionCopy the code
13. Dispatch_barrier_ sync (a) use?
A Dispatch barrier allows you to create a synchronization point in a concurrent queue. When a barrier is encountered in the concurrent queue, it delays the execution of the barrier blocks until all blocks committed before the barrier finish executing. At this point, the Barrier Block executes itself. After that, the queue continues to execute normally.Copy the code
14. What’s the difference between symmetric encryption and asymmetric encryption?
A: 1. Symmetric encryption is also known as public key encryption. Both encryption and decryption use the same key. The common symmetric encryption algorithms are DES, 3DES, AES, Blowfish, IDEA, RC5, and RC6. 2. Asymmetric encryption is also called shared key encryption. It uses a pair of asymmetric keys, one is called private key and the other is called public key. Public key encryption can only be decrypted using the private key, and private key encryption can only be decrypted using the public key. Common public key encryption algorithms include RSA, ElGamal, knapsack algorithm, Rabin (a special case of RSA), public key encryption algorithm in Diffie-Hermann key exchange protocol, and elliptic curve encryption algorithm.Copy the code
15. What are the benefits of componentization?
A: Business is layered and decoupled to make the code maintainable; Effectively break down and organize the increasingly large engineering code to make the engineering directory maintainable; It is convenient for the separation and withdrawal of each service function to realize the real function reuse; Business isolation, implementation of cross-team development code control and version risk control; Modularity has certain requirements on the encapsulation and rationality of the code, and improves the design ability of the development students; Under the condition of maintaining the components at all levels, arbitrarily combination to meet different customer needs; (The next brand new App can be quickly iterated by assembling previous business component modules in the new main App)Copy the code
16. How do you decouple components?
Answer: hierarchical basic functional components: according to the function of the Library, does not involve product business requirements, similar to the Library Library, through a good interface through the upper business components call; Do not write product customization logic, through the extension interface to complete customization; Basic UI components: each business module depends on each other, but the customized and extended design business components need to be maintained. Business functions are relatively independent, and there is no dependency on Model sharing. Page calls between services can only be skipped through UIBus; Logical Action calls between businesses can only be provided through services; Middleware: target-action, URl-block, and protocol-classCopy the code
Several implementations of iOS componentization schemes
17. What aspects of APP startup time should be optimized?
A: App start time can be measured using the tools provided by Xcode. Set DYLD_PRINT_STATISTICS to YES in Xcode's Product->Scheme-->Edit Scheme->Run->Auguments variable. The core idea of dylib loading time is to reduce the reference of dylibs and merge the existing Dylibs (preferably less than 6) using the static library rebase/ Binding time. The core idea is to reduce the pointer in the DATA block and reduce the Object C metadata quantity, reduce the number of Objc classes, reduce instance variables and functions (which conflict with object-oriented design ideas) reduce C ++ virtual functions, use Swift constructs (Swift is recommended) Initializer Time Use initialize instead of Load to reduce the use of C/C ++ attribute(constructor). Methods like dispatch_once(), pthread_once(), STD :once(), and so on are recommended for swift. Do not call dlopen() in the initialization, because the loading process is single-threaded, lockless. If you call dlopen, it will become multi-threaded, which will enable lock consumption. It is also possible to deadlock. Do not create threads during initializationCopy the code
IOS App Startup Process (I) : Basic concepts
IOS App startup process (part 2) : From exec() to main()
IOS App startup process (III) : main() and life cycle
Summary of Swift series interview questions
Basic questions:
1. The similarities and Differences between Objective-C and Swift?
A: 1.1. What SWIFT and OC have in common: most of the concepts used in OC, such as reference counting, ARC (automatic reference counting), attributes, protocols, interfaces, initializations, extended classes, named parameters, anonymous functions, etc., continue to be valid in SWIFT (possibly by changing terms at most). Swift and Objective-C share the same runtime environment. Swift types can be bridged to Objective-C (hereinafter referred to as OC) and vice versa. - SWIFT focuses on protocol oriented programming, functional programming, object-oriented programming, OC focuses on object-oriented programming - SWIFT focuses on value types, OC focuses on Pointers and references - Swift is a statically typed language, OC is a dynamically typed language - Swift is easy to read, The file structure and most of the syntax is simplified, only for.swift files, which do not require a semicolon at the end - the optional type in SWIFT is used for all data types, not just classes. Compared to nil in OC, it is safer and simpler to use generic types in -swift, which is more convenient and generic, whereas non-OC can only add generics to collection types. -Swift provides various convenient higher-order functions (functional programming). (Swift's standard array supports three higher-order functions: Map, Filter, and Reduce, and map extension flatMap) -swift Adds two types of permissions to refine permissions. Open > public > Internal (default) > Fileprivate > Unique tuples in private-Swift that combine multiple values into compound values. Values in tuples can be of any type; they do not have to be of the same type. - Functions can be used as parameters or return values in swift, but not in OC.Copy the code
Let’s make a distinction between Swift and Objective-C with emphasis
What is the difference between a class and a struct? What are the advantages and disadvantages of classes and structs?
A: The essential difference between the two: struct is a deep copy, copy is the content; Class is a shallow copy of the pointer. Struct is a value type, and class is a reference type. Variables of value type directly contain their data, and have their own copy of data for value types, so it is impossible to manipulate one variable to affect another. Variables of reference types store data references to them, so the latter are called objects, so operations on one variable may affect the objects referenced by another variable. Similarities: 1. You can define the following members: attribute, method, subscript, initializer 2. Both support type extension, protocol differences: 1. Classes support inheritance and polymorphism, structures do not support 2. Classes must define their own initializers, and structures will have a default member initializer 3. Classes support deinit, structs do not. 4. Instances of classes are on the heap, and ARC is responsible for releasing them. The struct is a copy of the value; the struct is a copy of the value; 6. Swift is a mutable variable, which is identified by var and let. If a variable is originally a let and then modified, a compilation error will occur. Structs follow this property; * Mutating function * mutating function * mutating function * mutating function * mutating function * mutating function * mutating function * mutating function * mutating function * mutating function * mutating function 8. Class supports reference equality comparisons (=== to! ==), the structure is not supportedCopy the code
Enumerations, structs, and classes
3. What is the difference between the associated value and the original value?
Enum Date {case digit(year: Int, month: Int, day: day) Int) case string(String) } 2. Raw value -- Enumeration members can be pre-associated with a default value of the same type. This default value is called: raw value // Raw value enum Grade: String { case perfect = "A" case great = "B" case good = "C" case bad = "D" }Copy the code
4. What is the difference between storage attributes and computing attributes in SWIFT?
A. Swift attributes related to instance objects can be divided into two categories: 1. Stored Property: Similar to the concept of member variables Stored in the memory of instance objects, classes can define Stored properties and enumerations can not define storage properties 2. Struct Circle {// store attribute var radius: // store attribute var radius: Var diameter: Double {set {radius = newValue / 2} get {return radius * 2}}}Copy the code
5.什么是延迟存储属性(Lazy Stored Property)?
A: Use lazy to define a deferred storage property that is initialized only when the property is first used (similar to lazy loading in OC). The lazy property must be var. If multiple threads access the lazy property for the first time at the same time, there is no guarantee that the property will be initialized only once. Image = { let url = "https://... x.png" let data = Data(url: url) return Image(data: data) }() }Copy the code
6. What is Operator Overload?
Struct Point {var x: Int var y: Int} // Static func + (p1: Point, p2: Point); Point) -> Point { return Point(x: p1.x + p2.x, y: p1.y + p2.y) } } var p1 = Point(x: 10, y: 10) var p2 = Point(x: 20, y: 20) var p3 = p1 + p2Copy the code
7. What is Optional, and how is Optional implemented
A: 1. In Swift, selectability is used to express the case that a variable is empty. When a variable is empty, its value is nil. 2.Optional is a generic enumeration defined roughly as follows: Enum Optional<Wrapped> {case none case some(Wrapped)} Let someValue: Int? Let optional1: Optional<Int> = nilCopy the code
8. What’s the difference between static and class when defining static methods
A: Methods defined by static cannot be inherited by subclasses, Class AnotherClass {static func staticMethod(){} class func classMethod(){}} class ChildOfAnotherClass: AnotherClass { override class func classMethod(){} //override static func staticMethod(){}// error }Copy the code
9. The use of the keywords Guard and defer in swift
A: Guard is also based on the Boolean value of an expression to determine whether a piece of code should be executed. Unlike the if statement, Guard executes this code only if the condition is not met. The guard let name = self.text else {return} defer is not executed immediately, but is pushed onto the stack until it is called again at the end of the function. Defer {// call until the function ends}Copy the code
10. What is the subscript in swift?
Subscript (subscript) : Subscript (subscript) : Subscript (subscript) : Subscript (subscript) : Subscript (subscript) : Subscript (subscript) : Subscript (subscript) : Subscript (subscript) Class Point {var x = 0.0, y = 0.0 subscript(index: Int) -> Double { set { if index == 0 { x = newValue } else if index == 1 { y = newValue } } get { if index == 0 { return X} else if index == 1 {return y} return 0}} var p = Point() p[0] = 11.1 p[1] = 22.2 Print (p.y) // 22.2Copy the code
11. Brief description of the initializer in Swift?
A: Classes, structs, and enumerators can all define initializers. Designated Initializer, Convenience Initializer // Specify initializer init(parameters) {statements} // Convenient initializer Convenience Init (parameters) {statements} Every class has at least one specified initializer, and the specified initializer is the primary initializer of the class. The default initializer is always the specified initializer of the class. The class prefers a small number of specified initializers, A class usually has only one designated initializer and the rules for mutual invocation of initializers say that initializer must call from its immediate parent class the designated initializer must call another initializer from the same class and the convenient initializer must eventually call a designated initializerCopy the code
12. What are the differences between init in Swift and OC?
A: The swift initialization method is more strict and accurate. The SWIFT initialization method needs to ensure that all non-optional member variables are initialized. At the same time, SWfit adds the tags convenience and Required. Convenience only provides a convenience initializer that must be initialized by a specified initializer. Required forces a child class to override the initialized method in its parent classCopy the code
13. Is Swift an object-oriented or functional programming language?
A: Swift is both object-oriented and functional programming language. Swift is an object-oriented language because it supports class encapsulation, inheritance, and polymorphism, in a way that is almost indistinguishable from a pure object-oriented language like Java. Swift is a functional programming language because it supports such methods as Map, Reduce, Filter, and Flatmap to eliminate intermediate states and mathematical functions, emphasizing the results of operations rather than intermediate processes.Copy the code
14. What are generics and where does Swift use them?
A: Generic allows us to define mutable parts of program code that can be specified at run time. Using generics maximizes code reuse, protects type security, and improves performance. Generics can parameterize types, increase code reuse, and reduce code volume. For example, map in Optional, flatMap,?? (Generics with escape closure, do trimesh)Copy the code
Swift generic
15. Swift Grammar sugar? ! Nature of (implementation principle)
A: Syntactic sugar is a special kind of syntax added to a computer language that has no effect on the functionality of the language itself, but is easier for programmers to use. Using syntactic sugar increases readability and optimizes code, thereby reducing errors. 3. If let and guard 4.?? 5.? And! ? Optional <T> is an enumeration that contains both nil and normal types, ensuring that the user handles the variable if it is nil! Mandatory unpacking syntax sugar for optionalCopy the code
16. What is a higher-order function
A: A function that takes a function as an argument or returns a value is called a higher-order function, such as map, Reduce, or FilterCopy the code
17. How do I solve reference loops
A: Only the class has a reference loop when converting to a value type, so you can dereferent the loop if you don't use the class. The delegate uses the weak attribute. In closures, use weak or unowned for objects where circular references might occurCopy the code
18. Describe and compare the following keywords: Open, Public, Internal, file-private, private
A: Swift has five levels of access control, in descending order, such as Open, Public, Internal, file-private and private. They follow the basic principle that high-level variables are not allowed to be defined as member variables of low-level variables. For example, a private class cannot contain a public String. Conversely, low-level variables can be defined in higher-level variables. For example, public classes can contain private ints. 1.Open has the highest access rights. Its decorated classes and methods can be accessed and overridden in any Module; It is a new access added to Swift 3. 2. The permission of Public is second only to Open. The only difference with Open is that it decorates objects that can be accessed in any Module, but cannot be overridden. 3.Internal is the default permission. It means that it can only be accessed and overridden in the currently defined Module. It can be accessed by multiple files in a Module, but not by other Modules. 4.File-private is also a new permission added to Swift 3. Its decorated object can only be used in the current file. For example, it can be used by classes, extensions, and structs in a file. 5.Private is the lowest access permission. Its objects can only be used within the scope defined. Outside this scope, even other scopes in the same file are inaccessible.Copy the code
19. Keyword :Strong,Weak,Unowned Difference?
A: The memory management mechanism of Swift is the same as that of OC. "Strong" and "Weak" are used the same as in OC. Unowned(no primary reference), no Strong reference will be generated, and the memory address of the instance (similar to unsafe_unretained in OC) will be retained after the instance is destroyed. Attempts to access the unretained reference after the instance is destroyed will result in a runtime error (wild pointer).Copy the code
20. How do I understand copy-on-write?
A: Value types (such as struct). When copied, the copied object and the original object actually point to the same object in memory. A new object is created in memory only if and when the copied object is modified. Struct, String, Array, Dictionary, Set uses Copy On Write technology. For example, if there is a "Write" operation, the actual Copy operation will be performed. For assigning to standard library value types, Swift ensures the best performance. Var str1 = "hi" var str2 = str1 print(str1) print(str2) /* str1 and str2 AppendContentsOf ("xixi") print(str1) print(str2) /* Str1 and str2 have different pointer addressesCopy the code
21. Why does Swift design String,Array, and Dictionary as value types?
Answer: The biggest advantage of value types over reference types is that they use memory more efficiently. Value types operate on the stack, and reference types operate on the heap. While stack operations are simply movements of a single pointer, heap operations involve merging, shifting, and relinking. Swift is designed to reduce the number of times memory is allocated and recollected on the heap, using copy-on-write to minimize value passing and replication overhead.Copy the code
22. What is attribute observation?
A: Attribute observation is to monitor and respond to attribute attributes within the current type. Attribute observation is a feature in SWIFT and has two types, willset and didSet var title: String {willSet {print("willSet", newValue)} didSet {print("didSet", oldValue, title)}} willSet It's called newValue by default, it's called oldValue by default, it's called oldValue and you set the property value in the initializer and it doesn't trigger willSet and didSetCopy the code
23. How to make some methods of the Protocol in Swift optional?
A: @objc protocol someProtocol {@objc optional func test()} @objc protocol someProtocol {@objc optional func test()} 2. Use extension to specify optional methods. In Swift, the protocol extension can define the default implementation of some methods protocol someProtocol{func test()} extension someProtocol{func test() { print("test") } }Copy the code
24. What are the differences between Swift and OC protocol?
A: The protocol in Swift and OC is similar in that both can be used as proxies. Differences: The protocol in Swift can also abstract the interface and implement protocol-oriented, thus greatly improving the programming efficiency. The protocol in Swift can be used for value types, structures and enumerations.Copy the code
25. What is the difference between introspection in SWIFT and OC?
A: [obj isMemberOfClass:[SomeClass class]] [obj isMemberOfClass:[SomeClass class] Because many classes do not inherit from NSObject, Swift uses is to determine whether it belongs to a type. Is applies not only to classes, but also to enums and structsCopy the code
26. What is function overloading? Does Swift support function overloading?
A: Function overloading refers to: the function name is the same, the number of parameters of the function is different, or the parameter type is different, or the parameter label is different, the return value type is irrelevant to function overloading swift supports function overloadingCopy the code
27. What does the closure structure look like in Swift? What is a trailing closure? What is an escape closure? What is an automatic closure?
1. {(argument list) -> return type in function body code}Copy the code
Answer: 2. If you need to pass a long closure expression as the last argument to a function, it is useful to replace the closure with a trailing closure. A trailing closure is a closure expression written after the function parentheses that the function supports calling as the last argument. // fn = exec(v1: Int, v2: Int, fn: (Int, Int) -> Int) {print(fn(v1, v2))} 20) {$0 + $1}Copy the code
Answer: 3. When a closure is passed as an argument to a function, but the closure is not executed until the function returns, the closure is said to escape from the function. When you define a function that accepts a closure as an argument, you can say before the argument name, @escaping, to indicate that the closure will allow "escaping" out of the function. Non-escape closures: the closure call occurs before the end of the function, the closure call escapes the scope of the function: the closure call may be called after the end of the function, the closure call escapes the scope of the function, We need to declare with @escaping // to define an array to store the closure type var completionHandlers: [() - > Void] = [] / / closures as actual parameters in the method, the storage to the external variable func someFunctionWithEscapingClosure (completionHandler: @ escaping () - > Void) {completionHandlers. Append (completionHandler} someFunctionWithEscapingClosure (_) function takes a closure as a parameter, The closure is added to an array defined outside the function. If you do not mark this argument as @escaping, you will get a compilation error.Copy the code
Answer: 4. Automatic closures take no arguments, defer evaluation, and return the value of the wrapped expression only when called. When we call function A to get the result of the function passed as an argument to function B, A will be executed regardless of whether the result is used in function B, such as the second call to goodAfternoon(afternoon: false, who: Func getName() -> String{print(#function) return "DKJone"} func goodAfternoon(afternoon:Bool ,who:String){ if afternoon { print("Good afternoon, (who)") } } print("------goodAfternoon(afternoon: true, who: getName())-------") goodAfternoon(afternoon: true, who: getName()) print("------goodAfternoon(afternoon: false, who: getName())-------") goodAfternoon(afternoon: false, who: getName()) /*log: ------goodAfternoon(afternoon: true, who: getName())------- getName() Good afternoon, DKJone ------goodAfternoon(afternoon: false, who: GetName ())------- getName() */ When we add @autoclosure to the second argument, the code in the second argument automatically generates a closure when the function executes, The second argument class code is only called when the closure is actually executed so the following goodMooning(morning: false, who: @autoclosure func goodMooning(morning:Bool,who:@autoclosure() -> String){if morning { print("Good morning, (who())") } } print("------goodMooning(morning: true, who: getName())-------") goodMooning(morning: true, who: getName()) print("------goodMooning(morning: false, who: getName())-------") goodMooning(morning: false, who: getName()) /* log: ------goodMooning(morning: true, who: getName())------- getName() Good morning, DKJone ------goodMooning(morning: false, who: GetName ())------- */ To avoid conflicting expectations, @Autoclosure will automatically encapsulate 20 as a closure {20}. @Autoclosure only supports arguments in () -> T Not only the last argument is supported with @autoclosure, no @autoclosure, which is a function overload. If you want autoclosure to allow escape, use both @autoclosure and @escaping.Copy the code
28. How to use singleton mode in Swift?
A: Singletons can be written using the type attribute +let+private; The code is as follows: public class FileManager {public static let shared = {//.... / /... return FileManager() }() private init() { } }Copy the code
29. What is the optional chain?
A: Optional chain is a process of calling and querying optional properties, methods, and subscripts, which can be nil. If the option contains a value, the call to the property, method, or subscript succeeds; If the option is nil, calls to properties, methods, or subscripts will return nil. Multiple queries can be linked together, and if any node in the chain is nil, the entire chain fails gracefully. More than one? You can link them together and if any node in the chain is nil, then the whole chain will failCopy the code
30. The difference between Extension in OC and Swift
Extensions add functionality to an existing class, structure, enumeration, or protocol type (63). Extensions add functionality to an existing class, structure, or protocol type (63). This includes the ability to extend types without access to the original source code (i.e., reverse modeling). The extension is similar to Categories in Objective-C. (Even more powerful, though, and unlike Objective-C, Swift's extension doesn't have a name.) Tip: Unlike OC, attributes cannot be added directly to Extension in Swift. The compiler will report an error. As with OC, we can add properties using the association method.Copy the code
Category and Extension — the difference between OC and Swift
The resources
IOS Learning Notes
IOS interview questions collated
Swift tutorial
IOS | knowledge to sort out the interview
conclusion
At present chengdu interview market is general, the requirements are not very high, the corresponding company to the salary package is not good. Many companies typically offer salaries between 8K and 11K, and it’s hard to move above that. Maybe I have not met the company with a good salary, personally think the interview questions are very different, or ask the bottom things, do not directly understand the situation. Personally, I suggest that for the sake of my future development, I should still choose a company that is difficult to interview. Maybe I can work hard for two years without an interview this time and then make an impact. Actually sometimes interview questions may we for poor understanding of the underlying knowledge, but the code is used a lot of, I am that kind of typical, the interview is very embarrassed ~, also blame yourself is project has dominated at ordinary times, many of them are used, but the lack of certain self summary, can’t say anything to cause. Ah, I hope we all encourage! Also hope that you can finally support me, my GitHub address: click to go to GitHub here: 1. Recommended life accumulated excellent Objective-C and Swift tripartite library 2. 3. The author found knowledge in daily learning 4. The accumulation of Swift development 5. The accumulation of learning Flutter is summarized and accumulated in my work. I hope it can help you. Thank you very much for these summary of the original, my daily mostly through these better quality of the article learning.