Objective-c, the strong and weak pointers under ARC are explained in principle

Source: Internet
Author: User

Objective-c, the strong and weak pointers under ARC are explained in principle

Tip: The "instance variable" in this article is "member variable" and "local variable" is

First, Introduction

ARC is a new feature that has been added since iOS 5, completely eliminating the cumbersome manual management of memory, and the compiler will automatically insert 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 attribute, not an IOS runtime feature (except for the weak pointer system), and it is not similar to a garbage collector in other languages. So ARC and manual memory management performance is the same, and sometimes faster, because the compiler can also perform some optimizations

Second, the principle

The rules of ARC are very 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 if the pointer no longer exists, the associated object is automatically freed. This rule is applicable for instance variables, synthesize attributes, and local variables.

Three, Strong hands

There is a text input box property in the controller

    1. @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 text property of the Namefield is a pointer to the NSString object, which is the owner, which holds the contents of the Text input box

2. If the following code is executed

    1. 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, which means that there are two pointers pointing to the same object

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

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

4. When the name variable gets a new value, or 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 owners, and the retain count drops to 0, when the object is freed

For example, assign a new value to the name variable

    1. Name = @"Jake";

We call the name and Namefield.text pointers "strong pointers" because they maintain the life of the object. Default all instance variables and local variables are strong pointers

Four, weak hands

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

    1. __weak nsstring *name = Self.nameField.text;


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

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

The weak pointer variable automatically becomes nil, which prevents the weak pointer from continuing to point to the disposed object, avoids the creation of a wild pointer, or causes a very difficult to find bug, with null pointers eliminating similar problems

The 3.weak pointer is primarily used for the "parent-child" relationship, where the father has a strong pointer to the son, so the father is the owner of the son, but in order to prevent the cycle of ownership, the son needs to use the weak pointer pointing to his father. A typical example is the delegate mode, where your viewcontroller has a uitableview through the strong pointer (Self.view), UITableView DataSource and delegate are weak pointers, Point to your Viewcontroller

V. Use of strong and weak hands note

1. The following code is problematic:

    1. __weak nsstring *str = [[NSString alloc] initwithformat:@"1234"];
    2. NSLog (@"%@", str); //Print Out is "(null)"

STR is a weak pointer, so the NSString object has no owner and is released immediately after creation. Xcode will also give a warning ("warning:assigning retained object to weak variable; Object would be released after assignment ")

2. The general pointer variable is strong type by default, so we generally do not add __strong to the strong variable, the following two lines of code are equivalent:

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

3. Attributes can be strong or weak, as follows

    1. @property (nonatomic, strong) NSString *name;
    2. @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 Nsarray, the object sends a release message and may be released immediately. Subsequent nslog () printing of the object will cause the app to crash

    1. ID obj = [array Objectatindex:0];
    2. [Array Removeobjectatindex:0];
    3. NSLog (@"%@", obj);

This code is perfectly legal in arc because the obj variable is a strong pointer that becomes the owner of the object, and removing the object from the 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 have to think about 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 works only with Objective-c objects, and if your app uses Core Foundation or malloc ()/free (), you need to manually manage the memory at this point

2> In addition to the arc there are some other stricter language rules to ensure that arc works properly

3. Although Arc manages retain and release, it doesn't mean you don't have to worry about memory management at all. Because the strong pointer maintains the life of the object, in some cases you still need to manually set these pointers to nil, which may cause the app to be out of 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 used in conjunction with 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

Vii. Summary of Arc use attention

1. You cannot call the Dealloc method directly, and you cannot call the Retain,release,autorelease,retaincount method, including @selector (retain), or 2. You can use the Dealloc method to manage some resources, But cannot be used to release instance variables, nor in the Dealloc method to remove the [Super Dealloc] method, under the arc of the parent class Dealloc also by the compiler to automatically complete the 3.Core foundation type object can still use Cfretain, Cfrelease these methods 4. Nsallocateobject and Nsdeallocateobject objects can no longer be used 5. Object pointers cannot be used in C structs, and if similar functions can be created a objective-c class to manage these object 6. There is no easy way to convert between ID and void*, and the same conversion between OBJECTIVE-C and core Foundation types requires a compiler-developed conversion function 7. You can no longer use the NSAutoreleasePool object, ARC provides a @autoreleasepool block to replace it, which makes it more efficient 8. Cannot use memory store (no longer nszone) 9. You cannot give a property a name starting with new 10. Weak is generally used when declaring iboutlet, In addition to storyboard such as nib middle of the top-level object to use strong 11.weak equivalent to the old version of Assign,strong equivalent to retain

Objective-c, the strong and weak pointers under ARC are explained in principle

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.