(iOS Interview Guide)

(# iOS classic Interview Questions 2021 (part 2)

1. Describe the common design patterns in your project. What are their advantages and disadvantages?

Common design patterns are: agent, observer, singleton.

(1) singleton: this is used to restrict the creation of only one object per class. Properties in this object can store globally shared data. All classes can access and set the property data in this singleton.

Advantage: It creates only one object that is easily accessible to the outside world, saving performance.

Disadvantages: it is that a class has only one object, which may cause excessive responsibility and violate the “single responsibility principle” to some extent. There is no abstraction layer in the singleton pattern, so it is very difficult to extend the singleton class. Do not create too many singletons, because singletons will exist from the time they are created until the program is closed. Too many singletons will affect performance and waste system resources.

(2) Observer (KVO) : it provides a way to observe a property change. When the properties of the specified object change, it automatically notifying the appropriate observers.

Advantage: Can provide new and old values for the observed property. Use the keypaths to look at attributes so you can look at nested objects as well.

Disadvantages: you need to register observers, implement observeValueForKeyPath: method, properties can be modified via KVC methods. Otherwise the observer will not be notified.

(3) Agent: it can realize one-to-one communication between classes.

Advantages: The proxy protocol methods are clearly defined. Proxy methods can be set optional or mandatory.

Disadvantages: Need to define the protocol method, need to set the proxy object, proxy object to implement the protocol method. In terms of memory management, you need to be aware of circular references.

2. Can the proxy mode realize one-to-many communication?

Yes, the way to implement multicast delegation. Multicast delegate: This is the ability to create call lists or linked lists of methods. The methods in the list are executed automatically when the multicast delegate is called.

The general proxy can only be a one-to-one callback, but not a one-to-many callback. The multicast delegate is a formal extension of the delegate, which requires a registration and cancellation process. Any object that requires a callback must first be registered.

3. Is there any problem with duplicate registration notification?

No problem. If you send the same notification more than once, the other party will respond more than once. If you register the notification twice, you will also have the effect of multiple responses. To avoid errors caused by duplicate notification registration, you are advised to remove a notification before registering it each time.

4. Have you used multithreaded programming in your project? Describe your common multithreaded implementations?

The common one is the GCD.

GCD is a multi-core programming solution developed by Apple. There are two types of GCD queues: SerialDispatchQueue and ConcurrentDispatchQueue. The system provides one dispatch_GET_MAIN_queue and one dispatch_GET_global_queue by default.

5. Describe the difference between NSOperationQueue and GCD.

(1) GCD is a low-level C language API. NSOperationQueue and related objects are Objc objects. In GCD, the tasks performed in the queue are made up of blocks, which are lightweight data structures. Operation, as an object, gives us more options.

(2) In NSOperationQueue, we can cancel tasks, but GCD cannot stop blocks that are already in the queue.

(3) NSOperation can conveniently set the dependency. You can also set the priority of NSOperation, enabling tasks in the same parallel queue to be executed sequentially. In GCD, we can only distinguish the priority of different task queues, and it takes a lot of complex code to distinguish the priority of block tasks. NSOperation can also set the concurrency.

6. What are the ways to implement multithreading?

(1) NSThread: detachNewThreadSelector:

(2) Inherit NSOperation

(3) GCD: dispatch_async

(4) NSObject: performSelectorInBackground:

7, what is KVC, KVO? Briefly describe the implementation principle of KVO. Can KVO listen on arrays? How?

KVC: Key-value encoding, which is an indirect mechanism for accessing instance variables of an object without access methods.

KVO: Key-value observation, which allows an object to get notification of changes in other object properties.

KVO is implemented based on isA-Swizzling technology, based primarily on runtime’s powerful dynamic capabilities. When a KVO listener is added to an object for the first time, the runtime dynamically creates a derived class of the object to be listened on and then overrides the setter method for the value of the property that KVO needs to listen on. The notification mechanism is implemented in the setter method. Finally point the ISA of the monitored object to a dynamically created derived class. Thus, when a property value is modified using KVC, the corresponding setter method in the dynamically created derived class is called, triggering the notification mechanism, thus implementing KVO. KVO can listen on arrays.

Implementation of NSMutableArray add, delete and change operation comply with THE rules of KVC, need to implement its corresponding methods:

Add -insert: inAtIndex: or -insert:atIndexes:

Delete operation -removeObjectFromatIndex: or -removeatIndexes:

Change operation – replaceObjectInAtIndex: withObject: or – replaceAtIndexes: with:

And expose these interfaces to the caller, who needs to use the interfaces of the above implementation when manipulating the array.

What’s the difference between C++, JAVA and Objective-C?

Objective-c and JAVA are both single-inheritance languages, while C++ is multi-inheritance languages.

Objective-c does not support a namespace mechanism and is distinguished by prefixing class names with NS.

Operator overloading is not supported in Objective-C and JAVA.

The Objective-C protocol is optional, but the JAVA interface must be implemented.

9. Is there a problem with adding nil elements to arrays? Can the dictionary object and key be set to nil?

We’re going to have a problem, we’re going to add nil to our array, we’re going to crash! Object cannot be nil The key of the dictionary cannot be nil, otherwise it will crash. The object of a dictionary cannot be nil.

Is there a problem with sending messages to a nil object in OC?

This is not a problem because OBJC is a dynamic language, and each method is dynamically converted to a message at run time. Objc_msgSend (Receiver, selector). When objc sends a message to an object, the Runtime library finds the actual class of the object based on the object’s ISA pointer, and then looks for methods to run in the list of methods in that class and the list of methods in its parent class. When objc_msgSend sends a message, the method returns no value. The so-called return content is the specific call at the time of execution. So, back to the point, if you send a message to a nil object, the first thing you’re looking for is an ISA pointer to the object and it’s returned at zero, so you don’t get any errors.

11. Are Mutable arrays Thread-safe? When is it unsafe? Can it be locked? Does it lock the add element operation or the array object?

Mutable arrays are not thread-safe and are not safe when reading data asynchronously. You can lock it. It locks the array.

Can I add a block to an array? If you add a block to an array and then pull it out, is that block still useful?

Yeah, it works. It’s just an extra retain

13. What’s the difference between setValue:forKey: and setObject:forKey: in NSMutableDictionary?

SetObject :forkey: value cannot be nil, otherwise an error will be reported.

The value in setValue:forKey: can be nil, but when the value is nil, the removeObject:forKey method is automatically called.

The key argument in setValue:forKey can only be of type NSString, whereas setObject:forKey can be of any type.

14, describe the difference between copy and mutablecopy.

(1) Non-container objects:

For immutable objects: copy is a pointer copy (shallow copy) and mutableCopy is an object copy (deep copy). For mutable objects: copy and mutableCopy are both object copies.

(2) Container objects:

For immutable objects: copy is a pointer copy, mutableCopy is an object copy.

For mutable objects: Copy and mutableCopy are both copies of objects, but they return different object types. The former returns an immutable object, while the latter returns a mutable object.

Container object replication is limited to the object itself; object elements are still pointer replication.

15, Describe the difference between weak and assign.

Weak is used to decorate objects. It cannot decorate basic data types. Assign is typically used to decorate basic data types. Weak modifies an object that is set to nil when it is released.

What are the default keywords when ARC does not specify any attribute keywords?

The basic data types are decorated by default with keywords: atomic, readWrite,assign

Plain OC objects are decorated by default with the keywords: atomic,readwrite,strong

17, When is weak empty?

Runtime lays out the registered classes, and puts a hash table for the Weak object. If the memory address of the weak object is a, it will search the weak table for all weak objects with a key, and set it to nil.

We can design a function (pseudo-code) to represent the above mechanism:

Objc_storeWeak (&a, b) function:

The objc_storeWeak function registers the second argument, the memory address of the assignment object (b), as key, and the first argument, the memory address (&a) of the weak modified property variable (a), as value. If the second argument (b) is 0 (nil), then to remove the memory address (&a) of the variable (a) from the weak table, you can interpret objc_storeWeak(&a, b) as: Objc_storeWeak (value, key), and when key changes to nil, set value to nil.

When B is non-nil, a and b point to the same memory address, and when B becomes nil, a becomes nil. Sending messages to A at this point does not crash: sending messages to nil in Objective-C is safe.

If a is assigned, then: if B is non-nil, a and B point to the same memory address, and if B is nil, a still points to that memory address, wild pointer. At this time, sending messages to A is easy to crash.

We’ll simulate “How Runtime implements weak” using pseudo-code based on the objc_storeWeak(&a, b) function:

// Use pseudocode to simulate how Runtime implements weak id obj1; objc_initWeak(&obj1, obj); / objc_destroyWeak(&obj1);

The two methods used, objc_initWeak and objc_destroyWeak, are explained below:

In general, what it does is: initialize “the variable with the weak modifier (obj1)” via objc_initWeak, and release the variable (obj1) at the end of its scope via objc_destoryWeak.

The following are the internal implementations of the methods:

The implementation of objc_initWeak looks like this: after initializing “variable with weak (obj1)” to 0 (nil), objc_storeWeak is called with an “assignment object” (obj) as an argument. Obj1 = 0; obj_storeWeak(&obj1, obj);

That is: the weak-modified pointer defaults to nil (it’s safe to send messages to nil in Objective-C) and then obj_destroyWeak takes 0 (nil) as an argument, and calls objc_storeWeak. objc_storeWeak(&obj1, 0); The previous source code is the same as the following.

// Use pseudocode to simulate how Runtime implements weak id obj1; obj1 = 0; objc_storeWeak(&obj1, obj); / *… Obj’s reference count goes to 0, it’s set to nil… */ objc_storeWeak(&obj1, 0);

The objc_storeWeak function takes the memory address of the second argument, the assignment object (obj), as a key, and registers the memory address of the first argument, the weak-decorated property variable (obj1), in the Weak table. If the second argument (obj) is 0 (nil), then remove the address of the variable (obj1) from the weak table.

The above contents are summarized as follows:

(1) Retrieve a record where the address of the discarded object is the key from the weak table

(2) Assign nil to the addresses of all __weak modifiers contained in the record

(3) Delete the record from the Weak table

(4) Delete the record where the address of the discarded object is the key value from the reference count table.

18. Have you used the automatic release pool? When was it released? When is an object added to the automatic release pool, and to which automatic release pool is it added?

Runloop is enabled on the main thread by default, and an Autoreleasepool is automatically created by runloop. Autorelease objects are automatically added to the Autoreleasepool, and the automatic releasepool is cleared after a runloop. Autoreleasepool is added automatically if __autoreleasing is used, or if a class method is created. It will be added to the latest Autoreleasepool.

19. Do you know what data persistence methods exist in iOS? Please explain briefly.

IOS data persistence methods include: SQLite3 database, CoreData, file archive, property list (PList file write).

Property list: The main class involved is NSUserDefaults, which stores small amounts of data.

File archiving: Objects must implement the NSCoding protocol. Implement the initWithCoder: method and encodeWithCoder method. It is also recommended to implement the NSCopying protocol.

SQLite3 Database :SQLite is an open source embedded relational database. Good portability, easy to use, requires a small memory overhead. Suitable for embedded devices.

CoreData: It can use SQLite to save data and does not need to write SQL statements. In addition, it can use XML to store data. To use CoreData, you need to design the entities and define their properties and relationships in the data model editor in Xcode. The data is persisted by manipulating these objects.

Is multithreading supported in FMDB? How it works!

Support multi-threading. It has an FMDatabaseQueue class in it. It looks like a queue, but it’s not, it inherits from NSObject, and internally creates a Serial dipatch_queue_t to handle incoming blocks from inDatabase and inTransaction, So when we call inDatabase or inTransaction on the main thread (or in the background), the code is actually synchronized. FMDatabaseQueue is designed this way to avoid the thread-safety issues of concurrent database access. All database access is performed synchronally, which is more efficient than @synchronized or NSLock.

Describe the difference between category and extension. When the Category and Extension load.

You can only add methods to a category, not instance variables (you can add properties). Extension can add not only methods, but also instance variables or properties (private). An extension cannot have a separate implementation part like a category. Category is determined at run time. Extension is compile-time determined.

Can category methods be inherited by subclasses? If it overrides the methods of the original class, can the methods of the original class be called? If you can, explain why.

Category methods can be inherited by subclasses. Category does not completely override the methods of the same name of the class, but the methods of category are ranked before the methods of the same name of the class, and the methods are retrieved sequentially, so when a method is called, the method of the same name is called category, resulting in an override. By traversing the list of methods at run time, methods overridden by a category can be called.

Extend a class with inheritance or category good? Please give your reasons.

Use categories. Because inheritance also requires defining subclasses. Classes do not require subclasses to add methods to existing classes. A method that overrides a class with a category is only valid for that category and does not affect the relationship of other classes to the original class.

How many types of blocks are there? Block implementation?

There are three types of blocks:

_NSConcreteGlobalBlock

_NSConcreteStackBlock

_NSConcreteMallocBlock

Block: Anonymous function

25. Do you use Swift much? A quick word about the difference between 1.0 and 2.0.

Swift2.0 added: Guard statement, exception handling, protocol extension, print statement change, Avaliable check, do-while statement renaming: repeat-while, defer keyword

Have you used the defer keyword in Swift?

The delay on the defer statement, called when the function ends.

27, SDWebImage where to save the image?

The images are kept in the sandbox under the Library/Caches folder.

Why can’t an instance variable be added to a class in Objective-C?

Because at run time, the memory layout of the object is already determined, adding instance variables would break the internal layout of the class.

Is the default protocol @optional or @require in Objective-C? What should I pay attention to when using the protocol?

The protocol in Objective-C must be implemented at @require. When using the protocol, you should pay attention to circular references. Multiple protocols are separated by commas.

30. What are the differences between objective-C protocols and JAVA interfaces?

OC protocol optional implementation, JAVA interface must be implemented.

31. What are the application scenarios of the class?

(1) It is possible to separate the implementation of a class into several different files

(2) Declare private methods

(3) Simulate multiple inheritance

(4) Expose the private methods of the Framework

What’s the difference between self and super?

Super is essentially a compiler identifier that points to the same message receiver as self. The difference is that super tells the compiler to call the class method to the superclass method, not the class method.

33. Why not save the image cache to the TMP file directory in the sandbox?

Because the TMP folder is used to store temporary files, iTunes does not back up and restore this directory, and files in this directory may be deleted after the application exits.

34. NSURLConnection and NSURLSession.

NSURLConnection Is an abstraction on top of the API of the CoreFoundation/CFNetwork framework.

The name NSURLConnection actually refers to a set of associated components in the Foundation framework’s URL loading system: NSURLRequest, NSURLResponse, NSURLProtocol, NSURLCache, NSHTTPCookieStorage, NSURLCredentialStorage and the namesake class NSURLConnection. The NSURLRequest is passed to the NSURLConnection. The delegated object (following the previous informal protocol and) asynchronously returns an NSURLResponse and an NSData containing the information returned by the server.

NSURLSession include: NSURLRequest, NSURLCache, NSURLSession, NSURLSessionConfiguration, NSURLSessionDataTask, NSURLSessionUploadTask, NSURLSessionD OwnloadTask. The difference between NSURLConnection and NSURLConnection is that the most immediate improvement of NSURLSession is the ability to configure the cache, protocol, cookie, and formal policy for each Session. Even share this information across programs. Each NSURLSession objects are initialized by a NSURLSessionConfiguration object. Session Task: Handles the loading of data and the last and last download of files and data between the client and server.

35. Describe the difference between ARC and MRC.

ARC: Automatic reference count. MRC: Manual reference counting. ARC leaves the memory in the hands of the system. The system will automatically insert retain/release at compile time. The MRC manually manages the reference count of objects. When you alloc, new, copy, mutablecopy or retain an object, you have an obligation to send a release or autorelease message to it.