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

@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 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

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

Name = @"Jake";

We call the name and Namefield.text pointers "strong pointers" because they maintain the life of the object. The default all instance 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

__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.subViews), UITableView's DataSource and delegate are weak pointers, pointing to your viewcontroller.

V. Use of strong and weak hands note

1. The following code is problematic:

__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 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:

NSString *name = Self.nameField.text;

__strong nsstring *name = Self.nameField.text;

3. Attributes can be strong or weak, 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 Nsarray, the object sends a release message and may be released immediately. Subsequent nslog () printing of the object will cause the app to crash. (Non-arc, required writing id obj = [[[Array Objectatindex:0] retain]; )

ID obj = [array Objectatindex:0]; Extracts an object with an index of 0 from an array of arrays and receives it with an obj variable.

[Array Removeobjectatindex:0]; Let array remove the object indexed as 0. (Non-Arc, object added to array, ownership is managed by arrays)

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. Cannot call the Dealloc method directly (nor in the Dealloc method to tune the [Super Dealloc] method), cannot call the Retain,release,autorelease,retaincount method, including @selector (retain) is not the way;2. You can use the Dealloc method to manage some resources, but not to release instance variables such as [Self.name release], 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, and objects of the 3.Core Foundation type can still be cfretain,cfrelease with 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 create a objective-c class to manage these objects, 6. There is no easy way to convert between ID and void*. Conversions between the OBJECTIVE-C and core Foundation types require a compiler-developed conversion function; 7. The NSAutoreleasePool object can no longer be used, and Arc provides a @autoreleasepool block to replace it. It's more efficient. ; 8. Cannot use memory store (no longer use nszone); 9. You cannot give a property a name starting with new; 10. When declaring Iboutlet, you should generally use weak, except for storyboard, the top-level object in the middle of the nib should be strong;11.weak equivalent to the old version of the Ign,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.