In Objective-C, the principles of strong and weak pointers under ARC are interpreted, and objective-cweak

Source: Internet
Author: User

In Objective-C, the principles of strong and weak pointers under ARC are interpreted, and objective-cweak

Tip: in this article, "instance variables" are "member variables" and "local variables" are "local variables"

I. Introduction

ARC is a new feature added since iOS 5, completely eliminating the hassle of manual memory management. The compiler will automatically insert appropriate retain, release, and autorelease statements in appropriate places. You no longer need to worry about memory management, because the compiler handles everything for you.

Note: ARC is a compiler feature, not iOS runtime feature (except weak pointer system). It is not similar to the garbage collector in other languages. Therefore, the performance of ARC is the same as that of manual memory management, and sometimes it can be faster, because the compiler can also execute some optimizations.


Ii. Principles

The ARC rule is very simple: as long as there is another variable pointing to the object, the object will remain in the memory. When the pointer points to a new value or the pointer no longer exists, the associated object is automatically released. This rule applies to instance variables, synthesize attributes, and local variables.


Iii. strong pointer

The Controller has a text input box attribute.

  1. @ Property (nonatomic, assign) IBOutlet UITextField * nameField;



1. If you enter the mj string in the text box

It can be said that the text attribute of nameField is the pointer of the NSString object, that is, the owner, which saves the content of the text input box.


2. If the following code is executed:

  1. NSString * name = self. nameField. text;

An object can have multiple owners. In the code above, the name variable is also the owner of this NSString object, that is, two pointers direct to the same object.


3. Then the user changes the content of the input box, such

The text attribute of nameFeild points to the new NSString object. However, the original NSString object still has an owner (name variable), so it will be retained in the memory.


4. when the name variable gets a new value or no longer exists (for example, when the local variable method is returned or the instance variable object is released), the original NSString object no longer has any owner, when the retain count is reduced to 0, the object will be released.

For example, assign a new value to the name variable.

  1. Name = @ "Jake ";



We call the name and nameField. text pointers as "Strong pointers" because they can keep the object lifecycle. By default, all instance variables and local variables are Strong pointers.


4. weak pointer

Weak pointer variables can still point to an object, but do not belong to the object owner.

1. Execute the following code:

  1. _ Weak NSString * name = self. nameField. text;


The name and nameField. text attributes both point to the same NSString object, but the name is not the owner.


2. If the content of the text box changes, the original NSString object will have no owner and will be released. At this time, the name variable will automatically become nil, which is called a null pointer.

It is very convenient to automatically change the weak pointer variable to nil, which prevents the weak pointer from pointing to the released object and avoids the generation of the wild pointer. Otherwise, it will lead to a very difficult-to-find Bug, null Pointer eliminates similar problems


3. the weak pointer is mainly used for the "Parent-Child" relationship. The father owns a son's strong pointer, so the father is the son's owner. To prevent the ownership loop, the son needs to use the weak pointer to direct to the father. A typical example is the delegate mode. Your ViewController has a UITableView through the strong pointer (self. view). The dataSource and delegate of the UITableView are both weak pointers pointing to your ViewController.


5. Use of strong and weak pointers

1. the following code is problematic:

  1. _ Weak NSString * str = [[NSString alloc] initWithFormat: @ "1234"];
  2. NSLog (@ "% @", str); // print it as "(null )"

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


2. Generally, pointer variables are of the strong type by default. Therefore, we do not add _ strong to strong variables. The following two lines of code are equivalent:

  1. NSString * name = self. nameField. text;
  2. _ Strong NSString * name = self. nameField. text;



3. the attribute can be strong or weak, which is written 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, this object will send a release message and may be immediately released. Then NSLog () prints the object, causing the application to crash.



  1. Id obj = [array objectAtIndex: 0];
  2. [Array removeObjectAtIndex: 0];
  3. NSLog (@ "% @", obj );

In ARC, this code is completely legal because the obj variable is a strong pointer and becomes the owner of the object. Removing this object from NSArray will not cause the object to be released.



Vi. ARC Summary

1. With the ARC, our code can be much clearer, and you no longer need to consider when retain or release objects. The only thing that needs to be considered is the association between objects, that is, which object owns which object?

2. There are also some limitations on ARC:

1> first, ARC can only work on Objective-C objects. If the application uses Core Foundation or malloc ()/free (), you need to manually manage the memory.

2> In addition, there are other stricter language rules for ARC to ensure that it works properly.

3. Although ARC manages retain and release, it does not mean that you do not need to worry about memory management at all. Because the strong pointer will keep the object's life, in some cases you still need to manually set these pointers to nil, otherwise it may cause insufficient application memory. Whenever you create a new object, you must consider who owns the object and how long the object will survive.

4. ARC can also be used in combination with C ++, which is very helpful for game development. For iOS 4, there is a little restriction on ARC (weak pointers are not supported), but it does not matter much.


VII. Summary of ARC usage


1. the dealloc method cannot be called directly. The retain, release, autorelease, and retainCount methods, including @ selector (retain), cannot be called. you can use the dealloc method to manage some resources, but it cannot be used to release instance variables or remove the [super dealloc] method from the dealloc method, in ARC, the dealloc of the parent class is automatically completed by the compiler. 3. the CFRetain and CFRelease methods can still be used for Core Foundation objects. you cannot use NSAllocateObject or NSDeallocateObject any more. object pointers cannot be used in the C struct. If similar functions are available, you can create an Objective-C class to manage these objects. 6. there is no simple conversion method between id and void *. Likewise, conversions between Objective-C and Core Foundation types must use the Conversion Function developed by the compiler. 7. you can no longer use the NSAID utoreleasepool object. ARC provides the @ autoreleasepool block to replace it, which is more efficient 8. you cannot use the memory storage zone (you cannot use NSZone again) 9. A new attribute cannot be named 10. weak is generally used to declare IBOutlet. Except for the top-level objects in nib such as StoryBoard, strong11.weak is equivalent to the assign of the old version, and strong is equivalent to retain.


Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.