Source code

Memory strategy

Although the work of the program is greatly restricted after entering the backstage, we never hope that the application will be killed by the operation system suddenly, and the important background work will be interrupted. Background applications are killed, affecting not just the user experience, such as the music being played, but the unexpected interruption of the voice being navigated. Because the operation system destroys the background application is not any kind of exception or operation error, the ability of the application to lose response to the accident is likely to destroy the important data accumulated in the single operation. Therefore, how to reduce the application in the background operation is a question worth pondering.

How backstage apps are killed

Put aside because the application is too long to be killed in the background, because memory problem is the most important reason. Memory differs greatly from other hardware resources.

When the demand for resources is more than the resources can supply, the performance of CPU decreases, and the operating system will kill the background application in order to recover memory.

We can divide the device memory into four parts, including system, background, foreground and free four parts.

  • System is fixed after the device is switched on and is almost impossible to access by our application.

  • Background belongs to the application run by the background. It will be recycled when it is short of memory.

  • Foreground belongs to the current running application memory.

  • Free belongs to allocable memory, and the system will allocate this part of memory to application.

Assuming that the device is switched on, the user opens your application directly. The memory of the device does not include the background part at this time.

When the application is withdrawn from the front desk, there will be enough free memory to allocate, so the system will not recover memory temporarily.

Then the user opens a new application, but the new application requires a lot of memory, which is beyond the available memory of the device.

So the system sends memory warning notification to your application. The system restores temporarily unused memory, and then has enough memory to use for new applications:

Or you didn't issue warning at all, your application was killed directly.

Memory warning

Memory warning memory warning will be issued in two ways, including notification and agent, when the system perceives that there may not be more free memory to use. Generally speaking, developers and systems will react to warning. According to the different roles of the processor, we can divide them into active strategies and passive strategies.

Memory classification

Before we understand the difference between the two coping strategies, we need to understand that for every running application, there are two types of memory that can be automatically cleared by the system: (memory limitation is active allocation, memory that can be released at any time).


The contents displayed on the left will be stored by array or dictionary. Most of the time, for a smoother effect, we may cache data outside the page, such as preloaded cells, pre computed height, etc. These data determine the current application state, content and so on, are active data. This part of memory will not be recovered by the system, and it will be kept until the application is terminated.


The right side stores data that may be used, for example, when the user enters the recommendation function, he requests a lot of data, and uses NSCache to cache in memory, so that the contents can be displayed quickly when re entering the recommendation page. This part of the data is obvious unused data. This part of the memory will be cleared directly after the system is quickly reused.

From the classification of memory, reducing the number of Dirty data and increasing Purgeable can reduce the pressure of memory usage.

Passive strategy

The reason why we should first talk about passive strategy is that the operating system has done some work before issuing the warning to try to solve the problem. Only by understanding these can we help us solve the problem.


It is said that the memory labeled Purgeable will be cleaned up by the system and then reused. This cleaning process occurs before issuing a warning. If there is enough memory available after cleaning Purgeable, no warnings will be issued. NSPurgeableData is a subclass of NSData, which provides an interface similar to dispatch_group_t, which uses an integer variable to store the usage state. When the duty is 0, it indicates that the data is in an unused state.

 NSPurgeableData *purgeableData = [[NSPurgeableData alloc] initWithBytes: fileData.bytes length: fileData.length]; 
[purgeableData beginContentAccess]; / / / / value +1, begin to use data}...


NSCache provides a simple interface similar to dictionary to let us access data while allowing us to set a maximum cache. The data of NSCache are considered to be Purgeable types. These data will be eliminated by the LRU algorithm when the cache reaches the maximum value, and will be recovered by the system before issuing the warning.

Memory warning

After cleaning up the Purgeable data, if the memory is not enough, the system will issue a memory warning to all the active applications at this time.

Active strategy

In terms of operation, the data of Purgeable need to be maintained by developers, which is more like an initiative mechanism. But when the mechanism is not enough memory, it will be automatically recovered by the system, without the need for developers to do more work, so I am classified as a passive strategy. The initiative strategy should be the work of developers after receiving memory warning:

 - (void) applicationDidReceiveMemoryWarning: (UIApplication *) application {/ / / release data cannot keep the application running
[self.database close];}} - (-) (()) (* *) (* *) {{} / /

Processing warning is almost the only effective means for developers, but this method is not entirely reliable. If there are memory warnings based on the system, there are several risk points:

  • Memory warning is issued for all running applications, which means that at the same time, CPU may be too busy to handle your work.

  • If it happens to belong to the rear column of the application queue, there will still be insufficient memory if Purgeable data is recovered and other applications respond to warnings. It may be killed directly without processing.

Therefore, even if dealing with warnings is almost the only way, we still have to think about other ways. If we map part of the data to disk, the application can run with minimum memory.

file map

File mapping is not a panacea. Every time the data is modified, it will be updated to the same location as disk. Even though SSD's access capability is already very strong, it is still a great expense. Your data should always satisfy these requirements before considering the use of file mapping:

  • Apply the necessary data for running. For example, music applications play music information, player classes.

  • The cost of construction or reduction is very high. If the cost is not high, then there is nothing to lose.

  • Data are easy to calculate. If the data always changes, it will cause serious interference to the calculation of file size.

  • The data are almost unchanged. The less the change, the higher the storage value.

These conditions determine that file mapping is not applicable to all data, and basically applies to configuration files, image data, text data and so on, and these data are often the bulk of memory.

In addition, if the amount of data is large, the data will be integrated into a large data segment. With the same data size, the memory efficiency of the system processing multiple block file mapping is much lower. In addition, too many virtual memory blocks can also cause the system to kill applications. NSData allows us to use options to provide file mapping:

 Typedef NS_OPTIONS (NSUInteger, NSDataReadingOptions) {
NSDataReadingMappedIfSafe = 1UL "0, 
NSDataReadingUncached = 1UL" 1, 
NSDataReadingMappedAlways API_AVAILABLE (MacOS (10.7), IOS (5), ((2)), ((9)) = "3", "}";


Because of the sandbox mechanism of apple, we used to pay more attention to the use of memory in the application, pay less attention to the memory problems that may be encountered when running in the background, and quote the apple engineer's words on WWDC video.

You should always think that something else outside your application will be hostile to you and destroy you.

Therefore, we need to learn how to use the strategy of memory usage reasonably to resist the attack from outside application. Of course, the most important thing is that we can confidently tell QA: hum, the memory usage of application has come down.

Author: sindri's nest


Fabulous ( One )

This article is composed of Contributor Creation, article address: Https://
Use Knowledge sharing signature 4 The international license agreement is licensed. In addition to the reprint / provenance, all originals or translations of this site must be signed before retransmission. The final editing time is June, 11, 2018 at 04:56 afternoon.

Hot articles