Objective-c memory overflow problem experience summary

The memory usage reference counting mechanism of the iOS platform, and the introduction of a semi-automatic release mechanism; this diversity of usage, causes developers to be very prone to memory leaks and inexplicable memory growth in memory usage; this article will introduce the iOS platform Memory usage principles and usage traps; in-depth analysis of autorelease mechanism; processing flow after low memory alarm; combined with own examples to introduce the problem tracking record of memory surge and the usage of related tools; 
common memory problems 
of iOS platform as a developer of iOS platform , Have you ever been troubled by memory problems? The inexplicable continuous growth of memory, the inexplicable crash of the program, and the inexplicable memory leaks are all common problems related to the memory of the iOS platform; this article will introduce the memory management mechanism, autorelease mechanism and memory usage traps of the iOS platform in detail. It will solve most of the problems on the memory of the iOS platform and improve the stability of the program; 
1 Introduction to the memory management of the 
iOS platform The memory management of the iOS platform uses a reference counting mechanism; when an object is created using the alloc or allWithZone method, the reference counting is Will be +1; when releasing an object using the release method, the reference count is -1; this means that each object will keep track of how many other objects refer to it, and once the reference count reaches 0, the memory of the object will be released; In addition, iOS also provides a delayed release mechanism AutoRelease. Developers do not need to manually release the memory requested in this way, and the system will release the memory at a certain time; due to the diversity of memory management on the iOS platform , Causing developers to easily experience memory leaks or inexplicable program crashes in memory usage. This article will introduce in detail the usage specifications and techniques of iOS platform memory and how to use tools to avoid or find problems; 
2 iOS platform memory usage principles 
2.1 Object Ownership and destruction 
2.1.1 Who created it and released it;
If the object is created with alloc, new or copy, mutableCopy, you must call the release or autorelease method to release the memory; 
if it is not released, it will cause a memory leak! 
2.1.2 Who retains, who releases it; 
if you send a retain message to an object, its reference count will be +1, you must send the release or autorelease method to release the memory or restore the reference count after use; 
if it is not released, it will cause a memory leak! 
2.1.3 Creating and did not retain, do not release; 
do not release those who are not their own alloc or retain an object, or the program will crash; 
do not release autorelease objects, otherwise the program will crash; 
the deep and shallow copy copy 2.2 object 
in general Copying an object includes creating a new instance and initializing the new instance with the values ​​in the original object. Copying the value of non-pointer instance variables is simple, such as Booleans, integers, and floating point numbers. There are two ways to copy pointer type instance variables . One method is called shallow copy, which copies the pointer value of the original object to the copy. Therefore, the original object and the copy share reference data. The other method is called 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 
deep copy process is to create a new object and the reference count of 1, and initializes the value of the old object with the new object; 
of ClassA objA * = [[of ClassA the alloc] the init];  
of ClassA objB * = [objA copy];
objB is a new object, The reference count is 1, and the data of objB is equal to the data of objA;
Note: objB needs to be released, otherwise it will cause a memory leak! 
2.2.2 shallow copy 
shallow copy processes are, without introducing a new object, the original object reference can count + 
of ClassA objA * = [[of ClassA the alloc] the init]; 
of ClassA objB * = [objA The retain]; 
Note : ObjB needs to be released to restore the reference count of objA, otherwise it will cause a memory leak! 
2.3 Method 2.3.1 Object Access attribute declarations and implementations 
common attribute type variable declarations include readonly, assign, retain and copy; and the system will automatically set and get function declares a variable property; 
Readonly attribute: Read only , Cannot be written; 
assign attribute: is the default attribute, assign directly, without any retention and release issues; 
retain attribute: will increase the reference count of the original object and release the original object before assigning it, and then perform the assignment; 
copy attribute: copies of the original object, and the object before the release of the original assignment, and then making an assignment; 
2.3.2 using the property declaration may bring risks 
when a non-pointer variables retain (or copy) this property, try not dominant Release this variable; just leave this variable blank; otherwise it is easy to cause excessive release and cause the program to crash; For example: 
the strName of the ClassA class is a variable of type NSString* and the declared attribute is retain;  
ClassA.strName = nil; / * Release the original object and assign null to this object*/
[ClassA.strName release]; /* strName memory may have been released, which will cause the program to crash */
The Assign attribute is generally used for non-pointer variables (boolean type, plastic, etc.); it belongs to the direct assignment type and does not need to consider the retention and release of memory; 
if a pointer type variable uses the assign type attribute, the reference may have been released Variable; cause the program to crash; For example: 
ClassB* obj =[[[ClassB alloc] init] autorelease]; 
…… 
ClassA.strName = obj; /* strName points to the memory address of obj */ 
When using ClassA.strName later because obj is autorelease may obj memory has been recovered; lead to invalid memory references, procedures Crash; 
3iOS 3.1 platform autoRelease mechanism automatically releases FAQ pool 
all the time in the development of iOS program, whether encountered in the slide list Inexplicable memory growth, memory growth inexplicably when pictures are accessed frequently, memory growth inexplicably when databases are frequently opened and closed... These are all thanks to the autorelease mechanism of iOS; the specific analysis is as follows: 
1: Sliding list At that time, the memory has increased inexplicably, and the reasons may be as follows: 
1: The reuse mechanism of UITableView is not used; it causes each display cell to be re-allocated by autorelease; it causes the memory of the cell to increase continuously; 
image is accessed frequently internal API of iOS will constantly allocate autorelease buffers to process the decoding and display of the images frequent access to network images causes the image cache to alleviate this problem; 
2: Each cell will display a separate UIView, and a memory leak occurs in the UIView, causing the cell's memory to grow continuously;
2: When the pictures are frequently accessed, the memory grows inexplicably; 
3: Frequent opening and closing of SQLite leads to continuous growth of memory; 
SQLite is frequently opened and closed, and the data buffer for reading and writing is large, so SQLite will When opening and closing, it will use autorelease to allocate 51K of memory; if there are a lot of access times , the memory will immediately reach tens of megabytes, or even hundreds of megabytes! Therefore, in the case of frequent reading and writing of the database and large data buffer, you can set the long connection mode of SQLite; avoid frequent opening and closing of the database; 
3.2 The concept of automatic release pool 
NSAutoreleasePool contains an array (NSMutableArray) inside to save the sound All objects named autorelease. If an object is declared as autorelease, the work done by the system is to add this object to this array. 
ClassA *obj1 = [[[ClassA alloc] init] autorelease]; //retain count = 1, add this object to the autorelease pool 
NSAutoreleasePool itself will traverse this array when it is destroyed, and release each member in the array. If the retain count of the members in the array is 1, then after the release, the retain count is 0, and the object is officially destroyed. If the retain count of the members in the array is greater than 1, then after the release, the retain count is greater than 0, the object is still not destroyed, and memory leaks. 
3.3 The scope and nesting of automatic release pool 
AutoreleasePool can be used nested!
The pool is nested, and the result of nesting is a stack. Only the current top pool instance of the same thread is available: 
 
when a short life cycle, such as a loop, a large amount of temporary memory will be generated, a temporary autorelease can be created pool, which can achieve the purpose of quickly reclaiming memory; 
3.4 Manual and automatic 
creation of automatic release pool 3.4.1 Need to manually create automatic release pool 
●If you are writing a program that is not based on Application Kit, such as a command line tool, there is no Built-in support for auto-release pools; you must create them yourself. 
● If you spawn a slave thread, once the thread starts executing, you must immediately create your own auto-release pool; otherwise, you will leak objects. 
● If you write a loop in which many temporary objects are created, you can create an auto-release pool inside the loop to destroy these objects before the next iteration. This can help reduce the maximum memory footprint of the application. 
3.4.2 The system automatically creates an automatic release pool 
Application Kit will automatically create an automatic release pool at the beginning of an event cycle (or event loop iteration)—such as a mouse down event—and release it at the end of the event cycle. 
4 iOS Platform memory usage traps 
4.1 repeat release 
have mentioned earlier, do not release the object is not to create their own; 
release their autorelease objects, app would crash; 
release system autorelease objects, app would crash; 
4.2 circular references  

Circular references are easy to produce wild references, memory cannot be recycled, and eventually lead to memory leaks! The chain of circular references can be broken by weak references; the so-called weak references do not require retain and direct assignment. In this way, the problem of circular references can be avoided, but it should be noted to avoid the problem of repeated release;  
5 iOS Platform memory alarm mechanism
due to iOS The platform's memory management mechanism does not support virtual memory , so if there is insufficient memory , it will not create virtual memory on Ram ; so once there is insufficient memory, the iOS platform will notify all running apps, whether it is a foreground app or App that hangs in the background will receive a memory warning notice; once the app receives a memory warning notice, it should reclaim variables that occupy a large amount of 
memory ; 5.1 Memory alarm processing flow 
1: The app receives a memory warning from the system notice; 
2: App release takes up a lot of memory; 
3: The system reclaims the autorelease object created by this app; 
4: When the app returns to the opened page, the system re-calls the viewdidload method, and the view reloads the page data; redisplays ; 
5.2 memory alarm test methods 
on simulate to simulate a low memory warning messages; 
iOS simulator -> hardware -> analog memory warnings; 
developers can simulate a low memory warning came on the phone in the case of the simulator, can be avoided due to low memory warning The inexplicable crash problem of the app that leads to; 
6 iOS platform memory check tool 
6.1 Compilation and analysis tool Analyze
iOS analysis tools can find warnings in compilation, hidden dangers of memory leaks, and even check out logic problems; therefore, the problems found by Analyze must be solved during the self-test phase to avoid serious bugs;  
hidden dangers of memory leak tips: 
Potential Leak of an object allocated on line ……
hidden dangers of data assignment tips: 
The left operand of …… is a garbage value; Hazard tips for object reference : 
Reference-Counted object is used after it is released; The 
above tips are all serious and may cause serious problems. Developers need to pay close attention! 
6.2 Memory detection tool 
6.2.1 Memory leak detection tool— 
Leak Leak tool can easily count all the memory leaks, and it can also display which line of code has memory leaks in that file, so that it is easier to locate the problem, and it is also more aspect ; But when Leak counts memory leaks, it will also count the memory in autorelease mode; so when we look for memory leaks, we can ignore the autorelease situation; 
Leak tool: 
You can quickly find the memory in the code through the Leak tool Leaks, through tools, you can quickly find the code segment where memory leaks occur: 
6.2.2 Memory surge detection tool— 
Allocations Allocations tool can easily list all allocated memory points, so that we can sort by the allocated memory size , In this way, it is easy to find out which points have the most memory allocated and are continuously allocated, so we can analyze these places that continuously allocate larger memory;



 
This tool will display all the places where memory is applied, and count the number and size of applications; from this list, you can find out the statements with the most memory applications and the largest memory applications; thereby analyzing which places use the most memory, and then optimize And improvement;

Guess you like

Origin blog.csdn.net/qq_27740983/article/details/50125223