IOS-memory Management Super Pit memory leak Qaq

Source: Internet
Author: User

?? Before the time was allocated to check the memory leaks this big pit, greatly frightened!!! The result also really jumped in, climbed for a long time have not climbed out qaq. Every day open leaks all kinds of love, and then saw a big wave of "magical" memory leak information, the head is big.

?? But although this is a big hole, but take advantage of this opportunity can put memory management knowledge to practice again. Perhaps most of the new projects are arc now, but in some real big projects, many of the code that qaq years ago (and actually years ago) will be reused, and the code will have many implementations using the MRC approach, Therefore, it is common to see code mixed with the two different memory management modes of arc and MRC in the project. Then the code for the arc file might invoke the code implemented by the MRC pattern, and of course there are the reverse cases.

?? In addition to the ARC and MRC mixes, there are times when there are many underlying libraries that are implemented in C + +, and these libraries also involve some OC-related library class calls, which can be a bit more complicated. = =, so the memory management of C + + is also necessary to understand drip ~ ~ ~

?? Qaq, the next part of the last section will briefly list some of the situations that have occurred in memory leaks. Finally, we will find that these problems are very simple, but ripe words good, diving drowned people ah!

First, the detection Tool introduction 1.1 Instrument-leaks,allocations,analyze

?? The tool I used to detect memory leaks is primarily the integrated leaks component in Xcode, which has a high accuracy rate (after all, the fruit family's son), and can look at a number of leaks such as the size of the leak, where it was generated, and its stack information. But here, "where the leak" does not necessarily locate a specific occurrence of the leak code, but the occurrence of the leaking object to initialize the allocation of memory, and then need to specifically analyze the object to investigate the cause of the leak.

Resources:
1. "Use instruments to locate memory Leaks for iOS apps"
2. "Leaks instrument"

?? The Allocations tool is a tool that tracks object memory allocated by the application. It is generally used to see if a memory leak occurs in a place where there is a suspected memory leak, by repeatedly manipulating the memory of some objects to be properly released. (= =.) I'm not using this here, which is an old way of detecting memory leaks, but it's also useful in some cases. )

Resources:
1. "iOS Performance Optimization: Instruments Tool's life-saving three strokes"
2. "iOS Performance Tuning series: Using allocation to dynamically analyze memory usage"

?? Analyze is a tool for static analysis of code. It can find some logic errors, memory leaks and declaration errors (unused variables) and so on. Some of the memory leak problems can be found here are some common circular references, CF library object is not released and other relatively simple problems, usually in other ways before the use of the way to detect, some simple problems first discovered and processed.

Resources:
1. "iOS Performance Tuning series: Analyze Static Analysis"
2. "Iphone development tools-performance optimization with Xcode profile and analyze"

1.2 Memory Detection Components

?? In addition, there are memory detection components in "implant" projects, such as the Facebook IOS memory detection Fballocationtracker/fbmemoryprofiler/fbretaincycledetector, Msleakhunter,mleaksfinder,pleaksniffer and so on.

?? The implementation principles of these components are very similar. The main is to flexibly use the rumtime mechanism in OC, as well as various OC object life cycle Management related characteristics. In order to monitor the memory of OC objects, these components are essentially monitored at the time when these objects are allocated and released, combined with the purpose of the system implementing memory leak detection for these object life cycle management methods.

?? For example, the need to monitor a Uiviewcontroller type of object, you can think of the VC in iOS life cycle management and Uinavigationcontroller is very important, because the latter is often used in iOS applications to manage a large number of VC jump control. So it is possible to consider the purpose of detecting whether a VC has a memory leak by monitoring Uinavigationcontroller's navigation stack. (usually the following methods will be hook)

?? For example, common NSObject objects, whose alloc and Dealloc methods are important in the object life cycle, are the methods that are called when allocating memory resources and freeing memory resources, respectively. Then you can consider the method swizzing method to replace the implementation of the two methods, Alloc and Dealloc, so that you can get some information about the object memory allocation.

?? The following is the principle of detecting VC memory leaks:

  1. How can I tell if the VC still resides in memory?
    Tips: Use an object pointed to by the weak pointer in arc to automatically set nil when the object is disposed to detect if the VC resides in memory.

  2. At what time does the VC detect a memory leak?
    Tips: By monitoring Uinavigationcontroller's navigation stack, you can determine the start and end of a VC's life cycle. When the VC is removed from the navigation stack and the VC's Viewdiddisappear method executes, it is considered that the life cycle of a VC is about to end. At this time, you can create a pointer to the VC weak, and initialize a timer to the VC delay scanning, and finally through the 1 method to determine whether the VC still resides in memory to determine whether the VC has a memory leak conclusion.


Second, the application of memory

As you can see from the Apple Developer documentation, there are three categories of memory for an app:

    1. Leaked memory: Memory unreferenced by your application that cannot being used again or freed (also detectable by using the Leaks instrumen T).

    2. Abandoned memory: Memory still referenced by your application that have no useful purpose.

    3. Cached memory: Memory still referenced by your application, might be used again for better performance.

?? Where the leaked memory and abandoned memories belong to should be released without releasing the RAM, are memory leaks, and Leaks tool is only responsible for detecting leaked memory, regardless of abandoned memory. Leaked memory is common in the MRC era, because it is easy to forget to call release, but the more common in the ARC era is that a circular reference is the result of a abandoned Memory,leaks tool that does not find such a memory leak and has limited application. (citation source "portal")


Iii. Practice 3.1 Object Memory management


1. In MRC mode, the object created by new, copy, Alloc mode, remember release. Generally, the release operation is performed in Delloc. Of course, the local production should also be released within the local.

Comments: hehe, in practice found the most problem is this. Especially in both ARC and MRC projects. = =. I guess one of the reasons may be that the subsequent code modifier did not realize that the currently modified file is MRC mode, so after adding some attributes or member variables, there is no timely release of resources after the Dealloc method or object has been used.


2. In MRC mode, send the retain message and remember to send the release message. Also consider whether you want to release the original object before sending the retain message to an object.

Met with a chestnut:

@interface classA{    NSString *_str;}- (void)functionA{    //正确的方式是这里要有: [_str release];    _str = [[NSString stringWithFormat:@"%d", @(213)] retain];    //后续代码...}- (void)functionB{    //正确的方式是这里要有: [_str release];    _str = [[NSString stringWithFormat:@"%d", @(213)] retain];//后续代码...}@end

Tips: One problem here is that the retain message is sent to an object in Functiona, and if the Functionb method is called again, the STR variable is re-assigned. At this point, if the release message is not first sent to STR, it causes a memory leak in the object referenced in Functiona.
For general use of local variables will remember to send retain after sending release, however, in the case of pest, member variables may be re-assigned in different methods, it is important to pay attention!


3. In both the MRC and ARC cases, objects created using the Core Foundation framework (the C language Implementation framework, which can be type-converted to objects in the Cocoa Foundation Library) require manual memory management. That is, you need to manually call Cfretain and cfrelease to manage object memory.

Tips: This situation has nothing to say, is to remember Cfretain, Cfrelease and retain, release the same as to appear ~

?? One more point is Core Foundation Cocoa Foundation the content of frame and object pointer conversions. The pointer-to- Cocoa Foundation Core Foundation pointer conversion takes into account ownership of the object to which it is directed. ARC provides 3 modifiers to manage. "Reference: iOS Core Foundation framework and Cocoa Foundation framework differences, CORE Foundation framework Reference"

    1. __bridge, do nothing, just convert. In this case:
      (1). Conversion from cocoa to core requires manual cfretain, otherwise the pointer passed out when the cocoa pointer is released is invalid.

      (2). Conversion from core to cocoa requires manual cfrelease, otherwise the object reference count is still 1 and will not be destroyed when the cocoa pointer is released.

    2. __bridge_retained, the Cfretain is automatically called after the conversion, which helps to automatically resolve the situation above (1).

    3. __bridge_transfer, the cfrelease is automatically called after the conversion, which helps to automatically resolve the situation above (2).


4. Use NSAutoreleasePool to create an automatic release pool, make sure that it sends a drain or release message. This creates an auto-release pool object that is freed and is added to the auto-free pool object to receive the release message and avoid a memory leak.

The Chestnuts encountered:

- (void)functionA{    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    NSString *str = [[NSString alloc] initWithFormat:@"%d", @(213)];    [str release];    //执行各种代码...    if (...){        //执行各种代码...        //问题就在这里:return 之前没有释放自动释放池!!!        //正确的做法,加上: [pool release];        return;    }    [pool release];}

Tips: Pest's case seems to be a very funny mistake, but in the actual combat has found two places ... So if you are using the auto-release pool in the MRC mode, remember to send the drain or release operation to the auto-free pool as well. If you use arc, it is not recommended that pest use the automatic release pool, but this is the way it is.

@autoreleasepool {    //Code benefitting from a local autorelease pool.}

?? Since it comes to the automatic release of the pool, let's take a brief look at its implementation, usage scenarios and some caveats. It also mentions that NSAutoreleasePool has two methods drain and release, the difference between the two can refer to these materials: "NSAutoreleasePool use the difference between drain and release" NSAutoreleasePool ". In addition, also found a good article explaining Autoreleasepool, inside also explained the Autoreleasepool release time, principle and so on: "Shady behind the autorelease."


5. The object returned by the function, whether to join the auto-free pool (deferred release). From the specification of memory management, if a function needs to return an object, the object should be added to the auto-release pool ("who creates, who releases")? Although it is said from a certain point of view, it is possible for the function caller to be responsible for the release of the object instead of being added to the auto-release pool. If the object returned by the function does not join the auto-free pool, and the function caller does not release the object externally, there is a possibility of a memory leak.

(1) Some objects in OC are created in several ways, such as NSString, Nsarray, Nsdictionary and the like (and their mutable type). These classes provide two types of creation, one is member function initwithxxx, the other is class function stringwithxxx, arraywithxxx (or array), dictionarywithxxx (or dictionary) These.
These methods are different, the first way the object produced requires manual release to free memory, the second way the resulting object has been added to the Autoreleasepool, do not need manual release to free memory. So in the project should also pay attention to these objects using different creation method of the different object management methods, for the two kinds of object generation, there are many discussions, let's see for yourselves ha haha haha.

Resources:
1. stringWithFormat vs. Initwithformat on NSString
2. Objective-c: Should nsstring use Initwithformat? Or a stringWithFormat?
3.Difference between [Nsmutablearray array] vs [[Nsmutablearray alloc] init]

(2) in which the runtime method is encountered class_copyIvarList , the class_copyMethodList objects returned by these methods are not manually released due to memory leaks. Because these are functions implemented by C, it is necessary to manually free the return value of the function, otherwise it will cause a memory leak. = =. Here also by the way to remind you usually need to pay attention to the implementation of the C + +, when you see Malloc/new allocated objects, you should check that the object has no corresponding free/delete operations, these places are often the memory leak.


3.2 Reference Loops

?? This is a case of memory leaks in both the MRC and the arc, especially in arc, which is generally the culprit if there is a memory leak. = =. And personally think that the reference cycle of this problem is the most difficult to find and analyze! When the project is very large, the module will be very complex, the dependence on a lot of, accidentally it is easy to produce a strong reference cycle of this phenomenon. Especially when using block, pay more attention to proper handling to avoid the occurrence of strong reference loops.

Follow up to be updated ....

IOS-memory Management Super Pit memory leak Qaq

Related Article

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.