Download from the ARC and arclive platforms

Source: Internet
Author: User

Download from the ARC and arclive platforms

What is ARC?

ARC is a new feature launched by iOS 5, which is called Automation Reference Counting ). Simply put, retain/release is automatically added to the Code. The Code that was manually added to handle the reference count of memory management can be automatically completed by the compiler.

This function starts to be imported in iOS 5/Mac OS X 10.7 and can be used in Xcode4.2. A simple understanding of ARC is to allow the compiler (LLVM 3.0) to automatically generate the reference count of instances to manage part of the code During code compilation through the specified syntax. One thing is that ARC is not a GC, but a Static Analyzer tool.

Change Point

Through a short piece of code, we can see the changes before and after using ARC.

 1 @interface NonARCObject : NSObject {     2     NSString *name;     3 }     4 -(id)initWithName:(NSString *)name;     5 @end     6     7 @implementation NonARCObject     8 -(id)initWithName:(NSString *)newName {     9     self = [super init];    10     if (self) {    11         name = [newName retain];    12     }    13     return self;    14 }    15    16 -(void)dealloc {    17     [name release];    18     [Super dealloc];    19 }    20 @end    
 1 @interface ARCObject : NSObject {     2     NSString *name;     3 }     4 -(id)initWithName:(NSString *)name;     5 @end     6     7 @implementation ARCObject     8 -(id)initWithName:(NSString *)newName {     9     self = [super init];    10     if (self) {    11         name = newName;    12     }    13     return self;    14 }    15 @end    
When we used Objective-C memory management rules, we often used the following guidelines:
  • When generating an object, use autorelease
  • When the object is replaced, autorelease is used before retain
  • When an object is returned in a function, use return [[object retain] autorelease];

After using ARC, we don't need to do this, even the most basic release.

 

Benefits of using ARC

What are the advantages of using ARC?

  • As you can see from the above example, it will be much easier to write Objective-C code in the future, because we don't need to worry about annoying memory management and worry about memory leakage.
  • The total amount of code is reduced, and it seems a little refreshing, saving labor.
  • High-speed code. The use of compilers to manage reference counts reduces the possibility of inefficient code.

 

Poor

  • Remember a bunch of new ARC rules-certain learning cycles are required for keywords and features.
  • Some old code is troublesome for third-party code. to modify the code, you must manually modify the compilation switch.

As for the second point, because the default ARC in XCode4.2 is the ON state, the error message of "Automatic Reference Counting Issue" is often found during compilation of the Old Code.

 

At this time, you can set "Objectice-C Auto Reference Counteting" in the project compilation settings to NO. As shown below.

 

 

If you only want to not adapt to ARC for a. m file, you can add-fno-objc-arc to the file to compile FLAGS, as shown in.

 

 

Basic ARC rules

  • Retain, release, autorelease, and dealloc are automatically inserted by the compiler and cannot be called in code.
  • Although dealloc can be overloaded, it cannot call [super dealloc]

Since ARC is not a GC and requires some rules to enable the compiler to support code insertion, you must understand these rules before writing robust code.

 

Objective-C object

Objects in ObjectiveC can be divided into Strong reference and Weak reference. When other objects need to be maintained, retain is required to ensure that the object reference count is increased by 1. As long as the owner of the object exists, the strong reference of the object will always exist.

The basic rule for object processing is

  • As long as the object owner exists (the object is strongly referenced), the object can be used.
  • If the owner of an object is lost, the object is discarded.

 

Strong reference)

 

(S1)

As the initial holder of the "natsu" String object, firstName is the Strong reference of the NSString type object.

(S2)

Here, the firstName is substituted into the aName, that is, the aName is also the owner of the @ "natsu" String object. For this object, the aName is also a Strong reference.

(S3)

Here, change the content of firstName. Generate a New String object "maki ". At this time, firstName becomes the owner of "maki", while @ "natsu" only has aName. Each string object has its own owner, so they all exist in the memory.

(S4)

Append the new variable otherName, which will become another holder of the @ "maki" object. That is, Strong reference of an NSString object.

(S5)

When otherName is substituted into aName, aName becomes the owner of the @ "maki" String object. The object @ "natsu" has no owner, and the object will be discarded.

 

Weak reference)

Next, let's take a look at the usage of Weak reference.

 

 

(W1)

As with strong reference, firstName is the holder of the string object @ "natsu. That is, Strong reference of the NSString type object.

(W2)

Use the keyword _ weak to declare weak references to the weakName variable and substitute firstName. In this case, although weakName is referenced by @ "natsu", it is still Weak reference. That is, although weakName can see @ "natsu", it is not its owner.

(W3)

FirstName points to the new object @ "maki" and becomes its owner, while the object @ "natsu" is discarded because no owner exists. At the same time, the weakName variable will be automatically substituted into nil.

 

Reference keywords

References to objects in ARC mainly include the following keywords. Variables defined by strong, weak, and autoreleasing are implicitly initialized to nil.

 

  • _ Strong

By default, variable Declaration includes the _ strong keyword. If no keyword is written for the variable, the default value is a strong reference.

 

  • _ Weak

As you can see above, this is a weak reference keyword. This concept is a new feature. It is imported from iOS 5/Mac OS X 10.7. Because this type does not affect the lifecycle of an object, if the object has no owner before, it will be discarded after being created, such as the following code.

1 NSString _ weak * string = [[NSString alloc] initWithFormat: @ "First Name: % @", [self firstName]; 2 NSLog (@ "string: % @ ", string); // string is empty at this time

If The OS version Deployment Target is set to a lower version, The current deployment target does not support automatic _ weak references will be reported during compilation, we can use the following _ unsafe_unretained.

Weak reference also has a feature, that is, when the parameter object loses its owner, the variable will be automatically paid to nil (Zeroing ).

 

  • _ Unsafe_unretained

Like _ weak, this keyword is also a weak reference. The difference between it and _ weak is whether to execute nil assignment (Zeroing ). However, you must note that the object indicated by the variable has been discarded and the address still exists, but the object in the memory is no longer available. If you still access this object, the "BAD_ACCESS" error will occur.

 

  • _ Autoreleasing

This keyword causes delayed release of the object. For example, if you want to upload an uninitialized object to a method and instantiate the object in this method, you can use _ autoreleasing. It is often used for processing the returned value of a function parameter, for example, the following example.

 1 - (void) generateErrorInVariable:(__autoreleasing NSError **)paramError {     2     ....     3     *paramError = [[NSError alloc] initWithDomain:@"MyApp" code:1 userInfo:errorDictionary];     4 }     5     6 ....     7 {     8     NSError *error = nil;     9     [self generateErrorInVariable:&error];    10     NSLog(@"Error = %@", error);    11 }    

Another example is that the return value of a function is applied for in the function. The following code is usually used when you want to release the function at the call end.

1-(NSString *) stringTest 2 {3 NSString * retStr = [NSString stringWithString: @ "test"]; 4 5 return [[retStr retain] autorelease]; 6} 7 8 // use ARC 9 10-(NSString *) stringTest 11 {12 _ autoreleasing NSString * retStr = [NSString alloc] initWithString: @ "test"]; 13 14 return retStr;

This keyword is used when the method parameter is id * and the object is autoreleased when the method is returned.

 

Summary

Today, we see the basic ARC usage rules

  • Retain, release, retain, and autorelease cannot be used in the code.
  • Do not reload dealloc (this function can be reloaded if processing other than the object memory is released, but [super dealloc] cannot be called)
  • NSAllocateObject and NSDeallocateObject cannot be used
  • Object pointers cannot be used in the C struct.
  • If the cast between id and void * requires a specific method (_ bridge keyword)
  • You cannot use the NSAID utoreleasepool, but you need the @ autoreleasepool block.
  • Attribute names starting with "new" cannot be used (if the following compilation error occurs, "Property's synthesized getter follows Cocoa naming convention for returning 'owner' objects ")

 

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.