Operating system memory FAQ

Source: Internet
Author: User
IOS memory Spike problem tracking and use traps (
08:11:57)

The memory of iOS platform uses the reference counting mechanism and introduces the semi-automatic release mechanism, as a result, developers are prone to memory leakage and inexplicable memory growth in terms of memory usage. This article will introduce the memory usage principles and usage traps of the iOS platform, and deeply analyze the autorelease mechanism; the process of handling low-memory alarms, and introduces the trace records of memory surges and the usage of related tools based on your instance;

IOS platform memory FAQ

As a developer of iOS platform, have you ever been troubled by memory problems? Memory continues to grow inexplicably, crash programs, and hard-to-find memory leaks are common issues related to the memory of the iOS platform. This article will introduce the memory management mechanism of the iOS platform in detail, the autorelease mechanism and memory usage traps will solve most of the memory problems on the iOS platform and improve program stability;
1 Introduction to memory management on iOS platform

The memory management of iOS platform uses the reference counting mechanism. when an object is created using the alloc or allwithzone method, the reference counting will be + 1. When the released object uses the release method, the reference count is-1, which means that each object will track the number of other objects that reference it. Once the reference count is 0, the memory of the object will be released. In addition, IOS also provides a latency release mechanism, autorelease, to apply for memory in this way, developers do not need to manually release, the system will release the memory at a certain time;
Due to the diversity of memory management on the iOS platform, developers are prone to memory leaks or program crashes during memory usage, this article will introduce in detail the usage specifications and skills of iOS platform memory and how to use tools to avoid or discover problems;

Is a complete example of memory from application to release:


2 iOS platform memory usage principles
2.1 object ownership and destruction
2.1.1 Who created and released;

If the object is created using alloc, new, copy, and mutablecopy, you must call the release or autorelease method to release the memory;
If it is not released, the memory will leak!
2.1.2 who retain and who releases;

If a retain message is sent to an object, the reference count will be greater than 1, the release or autorelease method must be sent after use to release the memory or restore the reference count;
If it is not released, the memory will leak!
2.1.3 not created and retain not released;

Do not release objects that are not alloc or retain, otherwise the program will crash;

Do not release the autorelease object, otherwise the program will crash;
2.2 object deep copy and shortest copy

Generally, copying an object includes creating a new instance and initializing the instance with the value in the original object. Copying a non-pointer instance variable is simple, such as Boolean, integer, and floating point. There are two methods to copy the instance variables. A method is called shortest copy, which copies the pointer value of the original object to the copy. Therefore, the original object and the copy share the reference data. Another method is deep copy, that is, copy the data referenced by the pointer and assign it to the instance variable of the copy.
2.2.1 deep copy

In the deep copy process, a new object is created and the reference count is 1. The new object is initialized with the value of the old object;

Classa * obja = [[classa alloc] init];

Classa * objb = [obja copy];

Objb is a new object with a reference count of 1, and the objb data is equivalent to the obja data;

Note: The objb needs to be released, otherwise it will cause memory leakage!
2.2.2 shallow copy

The process of copying objects is to add the reference count of the original object + 1 without introducing new objects.

Classa * obja = [[classa alloc] init];

Classa * objb = [obja retain];

Note: The objb must be released to restore the reference count of obja. Otherwise, memory leakage will occur!
2.3 Object Access Method
2.3.1 attribute description and implementation

Common attribute types declared by variables include readonly, assign, retain, and copy. The system automatically generates the set and get functions for the variables declared;
Readonly attribute: Read-only, not write;
Assign attribute: it is the default attribute and is directly assigned a value without any retention or release issues;
Retain attribute: The reference count of the original object will be increased, and the original object will be released before the value is assigned, and then the value is assigned;
Copy attribute: Copies the original object, releases the original object before the value assignment, and then assigns a value;
2.3.2 potential risks arising from the use of attribute declarations

When a non-pointer variable uses the retain (or copy) attribute, do not explicitly release the variable. Leave the variable empty. Otherwise, excessive release may occur, cause program crash; for example:

The strname of the classa class is a variable of the nsstring * type and the declared attribute is retain;

Classa. strname = nil;/* release the original object and assign a null value to this object */

[Classa. strname release];/* The strname memory may have been released, causing crash */

This type is generally used when the assign attribute is a non-pointer variable (boolean type, integer type, etc.); it is a direct value assignment type and does not need to consider memory retention and release;

If a pointer type variable uses the assign type attribute, it may reference released variables, resulting in program crash; for example:

Classb * OBJ = [[classb alloc] init] autorelease];

......

Classa. strname = OBJ;/* strname indicates the memory address of the OBJ */

When classa. strname is used in the future, because obj is autorelisted, The OBJ memory may have been recycled; as a result, the reference of invalid memory and the program crash;
3ios platform autorelease Mechanism
3.1 FAQs about automatic release pool

When developing iOS programs, have you ever experienced an inexplicable increase in memory when the list slides, and an inexplicable increase in memory when you frequently access images, the memory grows inexplicably when the database is frequently opened or closed ...... These are thanks to the IOS autorelease mechanism. The specific analysis is as follows:

1: When sliding the list, the memory increases inexplicably for the following possible reasons:

1: The reuse mechanism of uitableview is not used. As a result, every cell displayed is re-alloc using autorelease. As a result, the memory of the cell is continuously increased;

2: Each cell will display a separate uiview. Memory leakage occurs in the uiview, which leads to the continuous growth of Cell Memory;

2: Memory increases inexplicably when images are frequently accessed;

Frequent accesses to network images lead to IOS Internal APIs, which will constantly allocate buffer in the autorelease mode to process image decoding and display. Image cache can alleviate this problem;


3: frequent enable and disable SQLite, resulting in increasing memory;

When SQLite is frequently enabled and closed, and the buffer for reading and writing data is large, SQLite will use autorelock to allocate 51 KB of memory each time it is opened and closed; if the number of visits is large, the memory will immediately reach dozens of megabytes or even hundreds of megabytes! Therefore, you can set the SQLite persistent connection mode for frequent reads and writes to the database and large data buffer; Avoid frequent opening and closing of the database;
3.2 concept of automatic release pool

The nsmutablearray array is contained in the nsmutoreleasepool to save all objects named autorelease. If an object is declared as autorelease, the system will add this object to this array.

Classa * obj1 = [[classa alloc] init] autorelease]; // retain COUNT = 1, add this object to autorelease pool

During the destruction, the NSAID utoreleasepool traverses the array and each member in the release array. If the retain count of the members in the array is 1 at this time, after release, the retain count is 0, and the object is destroyed. If the retain count of the members in the array is greater than 1 at this time, the retain count is greater than 0 after release, and the object is still not destroyed, causing memory leakage.
3.3 automatic release pool scope and nesting
Autoreleasepool can be nested!

The pool is nested, And the nested result is a stack. The same thread is available only for the top pool instance of the current stack:


A large amount of temporary memory is generated in a short life cycle, such as a loop. You can create a temporary autorelease memory pool to quickly recycle the memory;
3.4 manually create and automatically create an automatic cast pool
3.4.1 you need to manually create an automatic release pool
● If you are writing a program that is not based on Application Kit, such as the command line tool, there is no built-in support for the automatic release pool; you must create them yourself.
● If you generate a subordinate thread, once the thread starts execution, you must create your own automatic release pool immediately; otherwise, you will leak the object.
● If you write a loop and create many temporary objects, you can create an automatic release pool within the loop to destroy these objects before the next iteration. This helps reduce the maximum memory usage of applications.
3.4.2 The system automatically creates an automatic release pool

Application Kit automatically creates an automatic release pool at the beginning of an event cycle (or an event loop iteration), for example, by pressing an event with the mouse, and releases it at the end of the event cycle.
4 IOS memory usage traps
4.1 repeated release

As mentioned above, do not release objects that are not created by yourself;
Release your own autorelease object, and the app will crash;
Release the system's autorelease object, and the app will crash;
4.2 circular references


Loop references are prone to wild references, and memory cannot be recycled, resulting in Memory leakage! Weak references can be used to break the circular reference chain. The so-called weak references directly assign values without retain. In this way, circular references can be avoided, however, it should be noted that repeated release should be avoided;
5. Memory Alarm Mechanism on iOS platform

Because the memory management mechanism of iOS platform does not support virtual memory, virtual memory will not be created on Ram when the memory is insufficient. Therefore, if the memory is insufficient, the iOS platform notifies all running apps that they have received the notice of memory warning, whether it is a foreground app or a suspended app in the background. Once the app receives the notice of memory warning, the variables that occupy a large amount of memory should be recycled;
5.1 memory alarm handling process

1: The app receives the memory warning notice from the system;

2: The app releases a large amount of memory;

3: The system recycles the autorelease object created by this app;

4: When the APP returns to an opened page, the system re-calls the viewdidload method to reload page data and re-display the page data;
5.2 memory alarm test method

You can simulate low-memory alarm messages on simulate;

IOS Simulator-> hardware-> simulated memory warning;

Developers can simulate low-memory alarms on mobile phones on simulators to avoid the inexplicable crash issue of apps caused by low-memory alarms;
6 IOS memory check tools
6.1 compile and analyze the tool analyze

The IOS analysis tool can discover the compiling warning, memory leakage risks, and even the logic problems. Therefore, you must solve the problems found by analyze in the self-test phase, avoid serious bugs;
Memory leakage hazards:

Potential leak of an object allocated on line ......
Tips for Data assignment risks:

The left operand ...... Is a garbage value;
Object Reference hidden danger prompt:

Reference-counted object is used after it is released;


The above prompts are serious and may cause serious problems. Developers should pay close attention to them!
6.2 memory detection tools
6.2.1 memory leak detection tool-leak

The leak tool can easily calculate all memory leakage points, and it can also be displayed in that file, which line of code has memory leakage, so it is easier to locate the problem and compare it; however, when calculating the memory leakage, leak also counts the autorelease memory. Therefore, we can ignore autorelease when looking for Memory leakage;

Leak tool:



The leak tool can quickly detect memory leaks in the code, and the tool can quickly find code segments with memory leaks:

6.2.2 memory spike detection tool-allocati *****

The allocatati ***** tool can easily list all allocated memory points, so that we can sort by allocated memory size, in this way, we can easily find out which nodes allocate the most memory and are allocated continuously. In this way, we will analyze these locations where the memory is continuously allocated;


This tool displays all the locations where the applied memory is located, and counts the number and size of applications. From this list, you can find the statements with the maximum number of Memory Applications and the maximum number of Memory Applications; in this way, we can analyze the most memory used, which can be optimized and improved;


It is sorted by the amount of memory applied for, so that you can easily understand which code applies for a large amount of memory;
7 References
Http://www.cocoachina.com/bbs/read.php? Tid = 15963
Why? Tid = 94017

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.