Detailed explanation of the arc memory management in IOS application development _ios

Source: Internet
Author: User

Hint: the "instance variable" in this article is "member variable", and "local variable" is "local variable"

0. Introduction
arc is a new feature that has been added since iOS 5, eliminating the cumbersome manual management of memory, and the compiler automatically inserts the appropriate retain, release, and autorelease statements where appropriate. You no longer need to worry about memory management, because the compiler handles everything for you
Note: ARC is a compiler feature, not an IOS run-time feature (except for the weak pointer system), nor is it similar to a garbage collector in other languages. So ARC and manual memory management performance are the same, sometimes faster, because the compiler can also perform some optimizations

I. Opening and banning of arc
There are probably 2 ways to convert non-ARC code to ARC code:
(1). Automatic conversion tool using Xcode
(2). Manually set some files to support arc

1, Xcode automatic conversion tool
Xcode with an automatic conversion tool that converts old source code into ARC mode
(1). Arc is an attribute of the LLVM 3.0 compiler, and an existing project may use the old gcc 4.2 or LLVM-GCC compiler, so you first need to set up the use of the LLVM 3.0 compiler:
(Currently used XCODE4.5,LLVM 3.0 has been upgraded to LLVM 4.1)

It is also best to select the other Warning Flags in warnings as-wall so that the compiler will check all possible warnings to help us avoid potential problems

(2). The Run static Analyzer option under Build Options is also best enabled, so that the static Code analysis tool is run to check our code each time the project is Xcode.

(3). Set the "Objective-c Automatic Reference counting" option to Yes, but the Xcode automatic conversion tool automatically sets this option, just to show you how to manually set the

(4). Turn on Xcode's automatic conversion tool

(5). Xcode will display a new window that allows you to select which files need to be converted

Click the Check button, Xcode may pop-up dialog box prompts the item can not be converted to arc, you need to be ready to convert (here temporarily omitted detailed instructions)
(6). If there is no warning or error, the prompt window will pop up:

(7). Click Next, after a few seconds, Xcode will prompt all the file's transformation preview, showing all changes to the source file. The left is the modified file, the right side is the original file. Here you can view Xcode changes in a file file to ensure that Xcode does not correct your source file:

Click Save to complete the conversion
(8). After automatic conversion, Xcode removes all retain, release, and Autorelease calls, which may cause other warnings, invalid syntax, and so on, which require manual modification of the Code
Note: Xcode's automatic conversion tools are best used only once, and multiple uses may present a more bizarre problem. If you have not converted all the files for the first time, Xcode will not actually perform any conversion operations when you later attempt to convert the remaining files. Therefore, it is best to complete the conversion at once, and files without conversion can be considered for manual modification
2, manually open some of the file arc
in compiler flags a column plus-FOBJC-ARC means to open the arc of the. m file

3, prohibit certain files of the arc

A column of compiler flags plus-FNO-OBJC-ARC means that the arc of the. m file is forbidden.


Second, the principle
The rule of ARC is simple: As long as there is another variable pointing to the object, the object remains in memory. When the pointer points to a new value, or the pointer no longer exists, the associated object is automatically freed. This rule applies to instance variables, synthesize properties, and local variables.

Three, strong pointers
There is a text input box property in the controller

Copy Code code as follows:

@property (nonatomic, assign) Iboutlet Uitextfield *namefield;


1. If the user enters the MJ string in the text box

Then it can be said that the Namefield Text property is a pointer to the NSString object, that is, the owner, which holds the contents of the Text input box

2. If the following code is executed

Copy Code code as follows:

NSString *name = Self.nameField.text;


An object can have multiple owners, and in the code above, the name variable is also the owner of the NSString object, that is, two pointers to the same object

3. The user then changed the contents of the input box, such as

At this point the Namefeild Text property points to the new NSString object. But the original NSString object still has an owner (name variable), so it continues to remain in memory

4. When the name variable obtains a new value, or when no longer exists (such as when the local variable method returns, the instance variable object is released), the original NSString object no longer owns any owner, and the retain count drops to 0, when the object is released
For example, give the name variable a new value

Copy Code code as follows:

Name = @ "Jake";


We call the name and Namefield.text pointers "strong pointers" because they can hold the object alive. The default all instance and local variables are strong pointers

Four, weak pointers
A pointer variable of type weak can still point to an object but not to the owner of the object
1. Execute the following code

Copy Code code as follows:

__weak nsstring *name = Self.nameField.text;

Both the name variable and the Namefield.text attribute point to the same NSString object, but name is not the owner

2. If the content of the text box changes, the original NSString object will not have the owner, will be released, the name variable will automatically become nil, called the null pointer

Weak-type pointer variable automatically become nil is very convenient, so that prevent the weak pointer to continue to point to the released objects, avoid the production of wild pointers, otherwise it will be very difficult to find the bug, the null pointer eliminates similar problems

The 3.weak pointer is mainly used for "parent-child" relationships, where the father has a son's strong pointer, so the father is the son's owner, but in order to stop the ownership cycle, the son needs to use the weak pointer to his father. A typical example is the delegate pattern, where your viewcontroller has a uitableview through the strong pointer (Self.view), UITableView and DataSource are delegate pointers, Point to your viewcontroller.

V. Attention to use of strong and weak pointers
1. The following code is problematic:

Copy Code code as follows:

__weak nsstring *str = [[NSString alloc] initwithformat:@ "1234"];
NSLog (@ "%@", str); Print out is "(null)"

STR is a weak pointer, so the NSString object has no owner and is released immediately after it is created. Xcode will also give a warning ("warning:assigning retained object to weak variable; Object would be released after assignment ")
2. The general pointer variable defaults to the strong type, so generally we do not add __strong to the strong variable, the following two lines of code are equivalent:
Copy Code code as follows:

NSString *name = Self.nameField.text;
__strong nsstring *name = Self.nameField.text;

3. The attribute may be strong or weak, as follows
Copy Code code as follows:

@property (nonatomic, strong) NSString *name;
@property (nonatomic, weak) ID delegate;

4. The following code may not work before arc, because in manual memory management, when an object is removed from the Nsarray, the object sends a release message that may be immediately released. Then NSLog () prints the object, causing the application to crash
Copy Code code as follows:

ID obj = [array objectatindex:0];
[Array removeobjectatindex:0];
NSLog (@ "%@", obj);

This code is perfectly legal in arc because the obj variable is a strong pointer, and it becomes the owner of the object, and removing the object from Nsarray does not cause the object to be freed

Six, Arc summary
1. With arc, our code can be much clearer, and you no longer need to consider when to retain or release objects. The only thing to consider is the association between objects, which object has which object?
2.ARC also has some limitations:
1> First arc can only work on the Objective-c object, if the application uses the core Foundation or malloc ()/free (), then you need to manually manage the memory
2> In addition, ARC has some more stringent language rules to ensure that the arc works properly
3. Although Arc manages retain and release, it does not mean that you do not need to care about memory management at all. Because the strong pointer keeps the object alive, in some cases you still need to manually set these pointers to nil, otherwise it may cause an insufficient application memory. Whenever you create a new object, you need to consider who owns the object and how long the object needs to survive.
4.ARC can also be a good combination of C + +, which is very helpful for game development. There is a little bit of restriction on iOS 4,arc (weak pointers are not supported), but it doesn't matter much.

Seven, ARC uses the note summary
1. You cannot call the Dealloc method directly, you cannot call the Retain,release,autorelease,retaincount method, including @selector ( Retain).
2. You can use the Dealloc method to manage some resources, but not to release the instance variables, or to remove the [super Dealloc] method inside the Dealloc method. The dealloc of the parent class under Arc is also automatically completed by the compiler
3.Core Foundation type objects can still be used cfretain,cfrelease these methods
4. You can no longer use the Nsallocateobject and Nsdeallocateobject objects
5. Object pointers cannot be used in C structures, and if there are similar features you can create a objective-c class to manage these objects
6. There is no simple conversion method between IDs and void*, and the conversion between OBJECTIVE-C and core Foundation types requires the conversion function set by the compiler to use
7. No more NSAutoreleasePool objects can be used, ARC provides a @autoreleasepool block to replace it, which is more efficient
8. Cannot use the memory store (no longer uses Nszone)
9. You cannot give a property a name of
10, starting with new. When declaring iboutlet, you should generally use weak, except for storyboard nib the middle top-level object to use strong
11.weak equivalent to the old version of Assign,strong equivalent to retain

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.