This column will be updated continuously — please pay attention to iOS friends!

(The answer is not unique, only for reference, there are benefits at the end of the article)

XIB vs. Storyboards

Advantages:

  • XIB: It provides a visual interface before compilation. You can drag controls directly, and you can add constraints to controls directly, which is more intuitive, and there is less code to create controls in the class file, which is quite simplified. Usually there is one class for each XIB.
  • Storyboard: Provides a visual interface, draggable controls, and constraints before compilation, which makes development more intuitive. In addition, a Storyboard can have many interfaces, and each interface corresponds to a class file. Through Storybard, you can intuitively see the structure of the entire App.

Disadvantages:

  • XIB: When requirements change, the XIB needs to be modified significantly, sometimes even re-adding constraints, resulting in longer development cycles. XIB loading is naturally slower than pure code. XIB is difficult to use for complex logic that controls how different content is displayed in different states. When a multi-player team or multi-team is developing, conflicts can easily arise if XIB files are launched, and conflict resolution is much more difficult.
  • Storyboard: As requirements change, the constraints on the Storyboard interface need to be modified, and as with XIB, constraints may have to be re-added, or adding constraints can cause a lot of conflict, especially in multi-team development. For complex logic to control different display content, it is difficult. When you have a multi-player or multi-team development, people are changing a storyboard at the same time, resulting in a lot of conflicts, which can be very difficult to resolve.

Memory usage and optimization considerations

  • Reuse problems: such as UITableViewCells, UICollectionViewCells, UITableViewHeaderFooterViews set the correct reuseIdentifier, fully reuse;

  • Make the views as opaque as possible: With opque set to NO, the layer’s translucence depends on the image and the resulting layer, improving performance;

  • Don’t use complicated XIB/ storyboards: All the resources the XIB/Storyboard needs, including images, are loaded into memory at load time, even if they won’t be used much later. The performance and memory of those with lazy loading compared to pure code writing is much worse;

  • Choose the right data structures: Learning to choose the array structures that are most appropriate for your business scenario is fundamental to writing efficient code. For example, an array: an ordered set of values. Queries using indexes are fast, queries using values are slow, and inserts/deletes are slow. Dictionary: Stores key-value pairs. It is faster to look them up by key. Set: an unordered set of values, quick to find by value and fast to insert/delete. Gzip/ZIP compression: When you download related accessories from the server, you can use gZIP/ZIP compression before downloading, which reduces memory size and speeds up the download.

  • Lazy loading: Lazy loading is used for data that should not be used. For views that do not need to be displayed immediately, use lazy loading. For example, the prompt screen displayed when a network request fails may never be used, so lazy loading should be used instead.

  • Data cache: The row height of the cell is cached, making reload data more efficient. For network data that does not need to be requested every time, it should be cached, either written to the database or stored in a PList file.

  • Handling memory warnings: Generally, memory warnings are handled uniformly in the base class, reusing expensive objects that do not immediately free the relevant resources: Some objects are slow to initialize, such as NSDateFormatter and NSCalendar, but they are inevitably needed. They are usually stored as properties to prevent repeated creation.

  • Avoid reprocessing data: Many applications need to load data, often in JSON or XML format, from the server for functionality. It is important to use the same data structure on the server and client side;

  • Use Autorelease Pool: When some loops create temporary variables to process data, the Pool is automatically freed to ensure timely release of memory;

  • Correctly select the image loading mode: UIImage loading mode

Xxiii: What are the core components of the componentization scheme based on CTMediator?

If the main APP calls A service A, then the following components are required:

  • CTMediator class, This class provides functions – (ID)performTarget (NSString *)targetName Action (NSString *)actionName Params (NSDictionary *) Params shouldCacheTarget:(BOOL)shouldCacheTarget; This function can be generated according to the targetName object, according to the selector actionName construction, then can use performSelector: withObject: method, the target to perform an action.
  • The implementation code for business A, plus A special class that executes the name format of the Target Action class: Target_%@, in this case Target_A. All methods in this class have names beginning with Action_, and when you need to pass arguments, you pass them in the form of NSDictionary*. The CTMediator class creates an object of the Target class and executes the method on it.
  • The CTMediator extension of business A declares all the external interfaces of business A with clear parameters, so that the external caller can easily understand how to call the interface. In the implementation of the extension, the Target and Action need to be hardcoded. Since the party responsible for the extension is the same as the party responsible for the business, this is not an issue.

Why is the CTMediator scheme better than the Router-based scheme?

Disadvantages of Router:

  • In the implementation of componentization, URL registration is not a necessary and sufficient condition. A component does not need to register its URL with the component manager, which would cause unnecessary resident memory. The purpose of URL registration is actually a service discovery process. In the iOS world, service discovery is not required by active registration, but by using Runtime. In addition, the maintenance of the registration part of the code is a relatively cumbersome thing, and each time a new call is supported, the registration list is maintained. It’s common to forget to delete items if a call is deprecated. Since Runtime does not have a registration process, there are no maintenance operations and maintenance costs are reduced. Since the automatic discovery of services is achieved through Runtime, the task of expanding the invocation interface is only in the respective module. Any new interface or new business is added, it does not need to be operated by the main project, which is very transparent.
  • In the iOS domain, componentized middleware must provide services for openURL, rather than openURL providing services for componentization. If the componentization scheme is based on openURL in the implementation of App, there is a fatal flaw: non-routine objects (objects that cannot be stringed into urls, such as UIImage) cannot participate in local inter-component scheduling.
  • The way urls are used in local calls is unnecessary. If the business engineer needs urls for local scheduling, it is inevitable to provide Params. The business engineer is confused about which Params to provide in the call.
  • To support passing unconventional parameters, Mogujie’s scheme uses protocol, which is intrusive. Because an object in a service needs to be invoked, it must conform to a protocol that can be invoked. However, this protocol does not exist in the current business domain. Therefore, the current business has to rely on the public protocol. This has a significant impact on future business migration.

Advantages of CTMediator:

  • When calling, distinguish between local application call and remote application call. Local application invocations service remote application invocations.
  • Components only expose the callable interface through Action, and the interface between modules is solidified in the target-Action layer, which avoids the intrusion on Business in the process of implementing componentization and improves the maintainability of componentized interfaces.
  • Easy to pass various types of parameters.

XXV: MVVM design pattern

The components are shown in the figure below:

In this design pattern, the core is the ViewModel, which is a special type of model that represents the state of the UI in the application. It contains the following:

  • Properties of each UI control. For example, the current text of the Text field control, whether a button is in the Enable state.
  • Actions that the view can perform, such as button clicks or gestures.

It’s easier to understand when you think of a ViewModel as a model of a view.

In the MVVM pattern, the relationship between the three components is simpler than in the MVC pattern, with the following strict rules:

  • The view references the ViewModel, but the reverse does not hold.
  • The ViewModel references the Model, but the reverse is not true.

If the above two rules are violated, it is the wrong MVVM implementation behavior.

Benefits of this model:

  • Lightweight view (controller), where all UI logic resides in the ViewModel.
  • Testability. You can run the entire application without a view.

How the release of weak is automatically set to nil

  • Runtime maintains a Weak table that stores all Weak Pointers to an object

  • The Weak table is a Hash table, Key is the address of the object, and Value is an array of Weak pointer addresses

  • When the object is reclaimed, through the layers of calls, the following method will eventually be triggered to set all the Weak Pointers to nil. * Runtime source, objc-weak.m arr_clear_deallocating function

  • The use of weak pointer involves adding, deleting, modifying, and querying Hash tables, which has some performance overhead.

27: HTTPS encryption principle

  • The server uses asymmetric encryption (RSA) to generate public and private keys

  • The public key is then sent to the client, and the server stores the private key

  • After obtaining the public key, the client generates a key that is used by the client to communicate with the server in the future

  • Then the client uses the public key to encrypt the key and sends it to the server

  • After the server obtains the encrypted key sent by the client, it uses the private key to decrypt the key, so that both parties can obtain the key for communication

What do you think caused the crash?

When an App exits on an iOS device, the OPERATING system generates a crash log and saves it on the device. The crash log contains a lot of useful information, such as the full stack trace and memory image of each executing thread, so that you can parse this information to locate the code logic at the time of the crash and find the reason for the App to blink.

Generally speaking, crash is caused by two kinds of problems: the crash caused by violating iOS rules and the crash caused by App code logic BUG

1. Bugs in application logic

  • SEGV (Segmentation Violation), invalid memory address, such as null pointer, uninitialized pointer, stack overflow, etc.
  • SIGABRT: Received Abort, either calling Abort itself or receiving a signal from outside;
  • SIGBUS: Bus error. Different from SIGSEGV, SIGSEGV accesses invalid addresses (such as virtual memory does not map to physical memory), while SIGBUS accesses valid addresses, but bus access is abnormal (such as address alignment problems);
  • SIGILL: Attempts to execute an illegal command that may not be recognized or authorized;
  • SIGFPE: Floating Point Error, mathematical computation-related problems (which may not be limited to Floating Point calculations), such as division by zero;
  • SIGPIPE: there is no process at the other end of the pipe to take over data; Common causes of crashes are code logic problems or resource problems, such as arrays out of bounds, access to wild Pointers or resources do not exist, or resource capitalization errors

2. There are three types of crash caused by violating iOS rules

  • The memory alarm blinks

    • When iOS detects low memory, its VM system sends a low memory warning notification and tries to reclaim some memory. If things don’t improve enough, iOS will kill the background app to reclaim more memory; Finally, if memory is still insufficient, the running application may be terminated. In Debug mode, you can actively write the action logic executed by the client to a log file, so that the program can write the memory warning logic to the log file. When the memory alarm in the following screenshot occurs, it is to remind the current client performance memory is tight. Memory allocation issues and memory Leaks can be found through the Allocations and Leaks module libraries in the Instruments tool.
  • Response timeout

    • Apple’s Watchdog mechanism kills an application when it doesn’t respond to certain events (such as start, hang, resume, or end) and generates a crash log.
  • User Forced Exit

    • When you see “user forced exit,” the first thing you might think of is to double click the Home button and then close the app. However, a crash log is usually not generated in this scenario, because after double clicking the Home button, all applications are in the background state, and the iOS may shut down the background process at any time. In this scenario, a crash log is generated when the application blocks the interface and stops responding. The “user forced exit” scenario is a slightly more complicated one: hold down the power button until the “slide shutdown” screen appears, and then hold down the Home button. At this point, the current application is terminated and a crash log of the corresponding event is generated.

Xxix: Analyze SDWebImage

1.SDWebImage image loading process

Entrance setImageWithURL: placeholderImage: options: first, according to the placeholderImage then SDWebImageManager according to URL starts processing images.

2. Enter the SDWebImageManager – downloadWithURL: delegate: options: the userInfo:, To SDImageCache download cache lookup images are from queryDiskCacheForKey: delegate: the userInfo:.

3. The first pictures from memory cache to find if there is a picture, if have image cache in memory, SDImageCacheDelegate callback imageCache: didFindImage: forKey: the userInfo: to SDWebImageManager.

4. SDWebImageManagerDelegate callback webImageManager: didFinishWithImage: to UIImageView + WebCache front-end display pictures, etc.

5. If the image is not in the memory cache, generate NSInvocationOperation and add it to the queue to check whether the image has been cached from the disk.

6. Try to read the image file in the cache directory of the hard disk based on the URLKey. This step is performed in NSOperation, so the result callback notifyDelegate: is performed back to the main thread.

7. If the image is read from the hard disk, add the image to the memory cache (if the free memory is too small, the memory cache will be emptied first). SDImageCacheDelegate callback imageCache: didFindImage: forKey: the userInfo:. Then call back to show the picture.

8. If you do not read from the hard disk cache directory images, point out the picture does not exist in all cache, need to download the pictures, the callback imageCache: didNotFindImageForKey: the userInfo:.

9. Share or rebuild a downloader SDWebImageDownloader to start downloading images.

10. Image download is done by the NSURLConnection, and the relevant delegate is implemented to determine the image download, download completed, and download failed.

11. The connection: didReceiveData: use ImageIO made according to the pictures download progress load effect.

12. The connectionDidFinishLoading: data download is completed to SDWebImageDecoder do image decoding process.

13. Image decoding is done in an NSOperationQueue without slowing down the main thread UI. If there is a need for secondary processing of downloaded images, it is best to do it here as well, it will be much more efficient.

14. In the main thread notifyDelegateOnMainThreadWithInfo: declare decoding, imageDecoder: didFinishDecodingImage: the userInfo: Call back to SDWebImageDownloader.

15. ImageDownloader: didFinishWithImage: callback told SDWebImageManager pictures download is complete.

16. Notify all downloadDelegates that the download is complete, call back to show the image where needed.

17. Save the image to the SDImageCache in both the memory cache and hard disk cache. Writing files to hard drive is also done with a separate NSInvocationOperation to avoid slowing down the main thread.

18.SDImageCache registers some message notifications when it is initialized, clears the memory image cache when memory warnings or falls back into the background, and clears expired images at the end of the application.

19.SDWI also provides UIButton+WebCache and MKAnnotationView+WebCache for easy use.

20.SDWebImagePrefetcher can be pre-downloaded images for subsequent use.

The principle diagram of the SDWebImage

The principle diagram of the SDWebImage

2. How does SDImageCache manage data?

SDImageCache is divided into two parts, one is the memory layer, one is the hard disk layer. The in-memory level is the equivalent of a cache, storing images as key-values. All cached images are cleared when memory runs out. The file system is searched for management, and the file replacement method is based on the unit of time, and the image files that are longer than one week are removed. When SDWebImageManager to SDImageCache resources, first search for the data of the memory level, if there is a direct return, no words to access the disk, read the picture from the disk, and then do Decoder, the image object in the memory level to do backup, and then return to call the layer.

3. Reasons for doing Decoder internally (typical space for time)

Since the imageWithData function of UIImage decompresses Data into ARGB images every time the drawing is done, there will be a decompression operation every time the drawing is done, which is very inefficient, but only requires instantaneous memory. To improve efficiency, the SDWebImageDecoder unzip the resources wrapped under Data and then draw them on another image, so that the new image does not need to be decompressed repeatedly

What about SEL and Method and IMP?

Method

Let’s look at the definition

1. runtime.h 2. /// An opaque type that represents a method in a class definition. Typedef struct objc_method *Method; 4. 5. struct objc_method { 6. SEL method_name OBJC2_UNAVAILABLE; 7. char *method_types OBJC2_UNAVAILABLE; 8. IMP method_imp OBJC2_UNAVAILABLE; 9.}Copy the code

A Method is a piece of code that can perform a function independently. For example:

1. - (void)logName 2. { 3. NSLog(@"name"); 4.}Copy the code

This code right here, it’s just a function.

Let’s look at the contents of the objc_method structure:

  • SEL method_name Method name
  • Char *method_types Method type
  • IMP method_IMP implementation

In this structure weight, we have seen SEL and IMP, indicating that SEL and IMP are in fact properties of Method.

Let’s move on to SEL.

SEL

So let’s look at the definition first

1. Objc.h 2. /// An opaque type that represents a method selector. Typedef struct objc_selector *SEL;Copy the code

Now, just to clarify the relationship between selectors and SEL, when I was writing this article, I was actually searching for selectors, until I looked at the definition of selectors, and I realized I was getting it wrong.

1. @property SEL selector;
Copy the code

In the documentation, the definition of a selector is declared like this, that is, a selector is an instance of SEL, and it’s only in iOS that we use selectors so much that we think of them as a concept.

What do you mean by selector? If you think about the stock market, for example, there are so many companies listed on nasdaq, and their names are very long, or there are companies with similar names, which are ** limited. So when the market goes to designate a stock, it’s very inefficient. When you’re in a hurry to buy a stock, you say to your broker, “Hi, Peter, buy me a hundred shares of Tuniu Limited Liability Company?” Maybe by the time you finish, the broker enters it and the market changes, so Nasdaq usually uses a code like “TOUR”. The selector here does a similar thing, which is it allows us to quickly find the corresponding function.

Here’s what the document says:

A method selector is A C string that has been registered (or “mapped”) with the objective-C runtime. Selectors generated by the compiler are automatically mapped by the runtime when the class is loaded.

In iOS, runtime maps all methodhash into the set via the load function while running. So at runtime, you can find selectors very quickly, without sacrificing too much performance because of the Runtime feature.

Since selector is a string, I think it should be a combination of className and method. There are two naming rules:

  • You can’t duplicate selectors for the same class
  • Selector can be repeated for different classes

One of the disadvantages of this is that when we’re writing C code, we often use function overloading, which is the same function name, different arguments, but that doesn’t work in Objective-C, because the selector only has the name of the method, no arguments, so there’s no way to distinguish between different methods.

Such as:

1. - (void)caculate(NSInteger)num;
2. 
3. - (void)caculate(CGFloat)num;
Copy the code

There will be an error.

We can only tell by name:

1. - (void)caculateWithInt(NSInteger)num;
2. 
3. - (void)caculateWithFloat(CGFloat)num;
Copy the code

IMP

Take a look at the definition of IMP

1. /// A pointer to the function of a method implementation. Typedef id (*IMP)(id, SEL...) ; 3. #endifCopy the code

This is a little bit easier to understand, it’s a pointer to the memory address of the final implementation.

In summary, in the iOS Runtime, Method implements a quick query Method and implementation through the selector and IMP properties, which relatively improves performance while maintaining flexibility.

31: How does Autorelease work?

  • Under ARC, we use @autoreleasepool{} to use an Autoreleasepool, actually UIKit via a RunLoopObserver Pop and Push the Autoreleasepool between the second Sleep of the RunLoop. The autorelease object generated by this Loop will be released to the compiler as follows:
1. void *DragonLiContext = objc_ AutoreleasepoolPush(); 2. // {} code 3. objc_ AutoreleasepoolPop(DragonLiContext);Copy the code
  • Release time: Release when the current RunLoop iteration ends.

Thirty-two: How ARC works

  • The ARC compiler has two parts: the front-end compiler and the optimizer

  • Front-end compiler: The front-end compiler inserts a release statement for each “owned” object. If the object’s ownership modifier is __strong, it is owned. If an object is created within a method, the front-end compiler automatically destroys it by inserting a release statement at the end of the method. Objects (instance variables/properties) owned by the class are released in the dealloc method. In fact, you don’t need to write dealloc methods or call the superclass dealloc methods, ARC will do everything for you automatically. In addition, the code generated by the compiler will perform even better than the release statements you wrote yourself, because the editor can make some assumptions. In ARC, there is no class to override the release method, nor is there any need to call it. ARC will optimize the call process by using objc_Release directly. And we do the same thing with Retain. ARC calls objc_retain instead of preserving the message

  • ARC optimizer: While the front-end compiler sounds great, sometimes there are several repeated calls to retain and release in your code. The ARC optimizer is responsible for removing redundant Retain and release statements, ensuring that the generated code runs faster than manual reference counting

Thirty-three: the user needs to upload and download an important information file, how should judge whether the user uploaded and downloaded successfully?

  • Verify file integrity with MD5! (It is not possible to judge the end of the current request or the end of the data received only by the code)
  • When the client uploads a file, it adds the MD5 value of the file in the request body to inform the server. After receiving the file, the server verifies the MD5 value of the received file and the MD5 value in the request body to determine whether the upload is successful
  • When the client downloads a file, it receives the MD5 value of the file sent by the server in the response header. After the file is downloaded, it compares the MD5 value of the downloaded file with the MD5 value in the response header returned by the server to determine whether the download is successful
  • MD5 is a one-way operation that converts an arbitrarily long data string into a short fixed-length value. No two strings should have the same hash value
  • MD5 verification can be used in many fields, such as confidential data verification, download file verification, plaintext password encryption, etc. Example of MD5 verification: Such as customer to our data center sync a file, the file using MD5 check, so customers in sending files at the same time, there will be sending a check code file, do after we get the file MD5 algorithm, the calculation results compared with the customer to send check code, if the customer agree that sending the file without error, Otherwise, the file is considered incorrect and needs to be resend.

Thirty-four: The role of the ISA pointer

  • An object’s ISA points to a class, a class’s ISA points to a meta class, and a metaclass isa points to the metaclass’s root class. Isa helps an object find its methods

  • Is a pointer to the Class type. Each instance object has a pointer to ISA, which points to the object’s Class, and there is also a pointer to ISA, which points to meteClass(metaclass). A metaclass holds a list of class methods. When a class method is called, it first looks for the implementation of the class method from itself; if not, the metaclass looks for the method from its parent class. Also note that a meteClass is also a class, which is also an object. Metaclasses also have isa Pointers, and its ISA pointer ultimately points to a root meteClass. The root metaclass’s ISA pointer points to itself, thus forming a closed inner loop.

35: How does NSURLsession improve over NSURLConnection?

  • You can configure caches, protocols, cookies, and credential policies per session, and even share this information across programs

  • The session of task. It handles the loading of data and the uploading and downloading of files and data between the client and server. NSURLSessionTask is most similar to NSURLConnection in that it is also responsible for loading data. The biggest difference is that all tasks share a common delegate that is their creator, NSURLSession.

What is the effect of using drawRect?

The drawRect method relies on the Core Graphics framework for custom drawing

  • Disadvantages: It handles touch events by forcing a redraw with setNeddsDisplay every time a button is clicked; And more than once, each single point event triggers two executions. From a performance point of view, this is bad for both CPU and memory. In particular, if we have multiple UIButton instances like this on our interface, that’s going to be bad

  • The method invocation mechanism is also very special. When you call setNeedsDisplay, UIKit will mark the current layer as dirty, but the original content will still be displayed. Until the next view rendering cycle, the Core Graphics context will be rebuilt for the layer marked as dirty, and then the data in memory will be recovered, and then the drawing will be done using CGContextRef

When does an unrecognized Selector exception occur? How to avoid it?

  • When a method is called on an object that does not implement the method, it can be resolved by “message forwarding”, and if it still fails, an unrecognized selector exception will be reported

  • Objc is a dynamic language. Each method is dynamically converted to a message at run time, i.e., objc_msgSend(Receiver, selector). The process is described as follows:

    • When OBJc sends a message to an object, the Runtime library finds the actual class that object belongs to based on the object’s ISA pointer and then looks for a method to run in the list of methods in that class and in the list of methods in its parent class and if it still doesn’t find the corresponding method in the uppermost parent class, The program will die at runtime and throw an exception unrecognized selector sent to XXX. But before that happens, objc’s runtime gives you three chances to save the program from a crash
  • Three chances to save the program from crashing

    • Method resolution: The objc runtime calls +resolveInstanceMethod: or +resolveClassMethod:, giving you the opportunity to provide a function implementation. If you add the function and return YES, the runtime will restart the process of sending the message once. If the resolve method returns NO, the runtime will move to the next step, message forwarding
    • Fast forwarding: realized – forwardingTargetForSelector: if the target object, the Runtime will call this method at this moment, give you the opportunity to put forward this message to other objects As long as this method returns not nil, and the self, The whole process of sending the message will be restarted, and of course the object you sent will become the object you returned. Otherwise, it would continue Normal Fowarding. It’s called Fast, just to distinguish the next forwarding mechanism. Because this step doesn’t create any new objects, but the Normal Forwarding Invocation creates an NSInvocation object, and it’s much faster than Normal forwarding, so it’s called Fast Forwarding
    • Normal Forwarding is Runtime’s last chance to save you. First of all, it will send – methodSignatureForSelector: message function parameters and return values of the type. If – methodSignatureForSelector: returns nil, the Runtime will send – doesNotRecognizeSelector: news, program will hang up now. If a function signature is returned, Runtime creates an NSInvocation object and sends the -forwardInvocation: message to the target object

38: What are the common data storage methods in iOS?

  • comprehensive

    • All local persistent data stores are written to files by nature and can only be stored in sandboxes.
    • Sandbox is apple’s security mechanism, which essentially means that each application is assigned a folder to store data, and each application can only access the folder assigned to it. Other applications’ folders are not accessible.
    • At its core, data stores are written files. There are four main types of persistence: property list, object serialization, SQLite database, and CoreData
    • Property list: Applies to a small number of data stores, such as logged-out user information, application configuration information, etc. Only NSString, NSArray, NSDictory, NSData can WriteToFile; Storage is still a PList file, plist file can store 7 types of data: array, dictory, string, bool, data, date, number.
  • detailed

    • Object serialization: finally, it is saved as a property list file. If the program needs to store, it is more convenient to store the object directly. For example, there is a setting class, we can store the object of the setting class directly, there is no need to save each property in the file. Object serialization is taking an object that implements the NSCoding protocol, using the form of serialization (NSKeydArchiver), extracting the properties from the object, and turning them into a binary stream, which is NSData, NSData can be written to file or stored in NSUserdefault. Two methods that must be implemented encodeWithCoder, initWithCoder. The nature of object serialization is object NSData.
    • SQLite: Suitable for large, repetitive, and regular data storage. And frequently read, delete, and filter data, which is suitable for using databases (iOS uses third-party FMDB)
    • CoreData: Sqlite is a relational database. CoreData is based on the idea of or-mapping. O stands for Object, R stands for relationship, and Mapping stands for Mapping. Simplify the programmer’s burden and operate the database in an object-oriented manner. ORMapping is an idea. CoreData implements this idea. In Java, Hibernate is also an implementation of ORMapping, which is only implemented in Java.
    • CoreData is essentially a database, but it’s much more object-oriented. Instead of focusing on two-dimensional table structures, you only need to focus on objects, pure object-oriented data manipulation. When we use a database directly, if we insert data into the database, it is usually a one-to-one mapping of the attributes of an object to the fields of a table in the database, and then the attributes of the object are stored in the specific table fields. When fetching a row of data from a table, it also needs to be encapsulated in the attributes of the object, which is a bit tedious, not object-oriented. The problem CoreData solves is that you don’t need this intermediate transformation process. It looks like you just store the objects in and out, and you don’t care about the table, but you actually do the mapping internally.

39: Describes the life cycle of a ViewController

  • When we call the VIEW of UIViewControlller,
  • The system first determines if the current UIViewControlller has * views. If so, it returns a view.
  • If not, the loadView method is called,
  • Then determine if the loadView method is a custom method,
  • If it’s a custom method, it executes the custom method,
  • If not, determine whether the view controller has * xiB and stroyBoard.
  • Load the XIB and StroyBoard if they exist.
  • If you don’t create a blank view.
  • Call the viewDidLoad method.
  • And then we go back to view

Can global, global, and local static variables be modified in a Block?

  • Yes. Delve into how Block captures external variables and __block is implemented

    • Global variables and static global variables change in value, and they are captured by the Block because they are global and have wide scope

    • Static and automatic variables, captured by blocks from the outside, become members of the __main_block_IMPL_0 structure

    • Automatic variables are passed by value to the Block constructor. Block only captures variables that will be used in the Block. Since only the value of the automatic variable is captured, not the memory address, the value of the automatic variable cannot be changed inside the Block.

    • The external variables that Block captures that can change value are static variables, static global variables, and global variables

    • There are three types of blocks

      • _NSConcreteStackBlock: Blocks that use only external local variables and member property variables and do not have strong Pointers are stackblocks. The life cycle of a StackBlock is controlled by the system. Once a StackBlock returns, it is destroyed by the system and does not hold objects

        • As soon as the _NSConcreteStackBlock field ends, the Block will be destroyed. In ARC, the compiler automatically copies blocks from the stack to the heap. For example, when a Block is returned as a function, it will copy onto the heap
      • _NSConcreteMallocBlock: A block that has a strong pointer reference to a member property or a copy modifier will be copied to the stack as a MallocBlock. Without a strong pointer reference, it will be destroyed. The life cycle is controlled by the programmer and holds the object

      • _NSConcreteGlobalBlock: A block that uses no external variables or only global or static variables is _NSConcreteGlobalBlock and has a lifetime from creation to the end of the application and does not hold an object

  • In an ARC environment, once a Block is assigned, a copy is triggered, __block is copied to the heap, and a Block is also __NSMallocBlock. ARC environments also have __NSStackBlock, in which case __block is on the stack

  • In ARC, if a Block refers to an ID type, it is an retain. If a base variable does not have an __block, it cannot change its value. If a base variable does, it must change its structure so that its internal forwarding pointer points to the address after the copy

Portal:

IOS Interview collection + Answer (1) (juejin.cn)

IOS Interview collection + Answer (3) (juejin.cn)

IOS Interview collection + Answer (4) (juejin.cn)

IOS Interview collection + Answer (5) (juejin.cn)

IOS Interview Guide (QQ.com)