What is ARC?
- Change Point
- Benefits of using ARC
- Poor
Basic ARC rules
- Objective-C object
- Reference keywords
Summary
At the beginning of the new year, Vientiane was updated. From the beginning of the new year, let's take a closer look at the iPhone development. First, let's take a look at ARC.
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 for code analysis.
Change Point
Through a short piece of code, we can see the changes before and after using ARC.
- @interface NonARCObject : NSObject {
- NSString *name;
- }
- -(id)initWithName:(NSString *)name;
- @end
-
- @implementation NonARCObject
- -(id)initWithName:(NSString *)newName {
- self = [super init];
- if (self) {
- name = [newName retain];
- }
- return self;
- }
-
- -(void)dealloc {
- [name release];
- [Super dealloc];
- }
- @end
- @interface ARCObject : NSObject {
- NSString *name;
- }
- -(id)initWithName:(NSString *)name;
- @end
-
- @implementation ARCObject
- -(id)initWithName:(NSString *)newName {
- self = [super init];
- if (self) {
- name = newName;
- }
- return self;
- }
- @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
- The object can be used as long as the object owner has a strong reference ).
- 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.
By default, variable Declaration includes the _ strong keyword. If no keyword is written for the variable, the default value is a strong reference.
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.
- NSString _ weak * string = [[NSString alloc] initWithFormat: @ "First Name: % @", [self firstName];
- 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 ).
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.
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.
- - (void) generateErrorInVariable:(__autoreleasing NSError **)paramError {
- ....
- *paramError = [[NSError alloc] initWithDomain:@"MyApp" code:1 userInfo:errorDictionary];
- }
-
- ....
- {
- NSError *error = nil;
- [self generateErrorInVariable:&error];
- NSLog(@"Error = %@", error);
- }
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.
- -(NSString *) stringTest
- {
- NSString * retStr = [NSString stringWithString: @ "test"];
-
- Return [[retStr retain] autorelease];
- }
-
- // Use ARC
-
- -(NSString *) stringTest
- {
- _ Autoreleasing NSString * retStr = [NSString alloc] initWithString: @ "test"];
-
- 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.
- If dealloc is not overloaded for processing other than the object memory, this function can be reloaded, 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 _ bridge keyword)
- You cannot use the NSAID utoreleasepool, but you need the @ autoreleasepool block.
- The attribute names starting with "new" cannot be used. If this attribute name is used, the following compilation error occurs: "Property's synthesized getter follows Cocoa naming convention for returning 'owned 'objects ")
Address: http://www.yifeiyang.net/development-of-the-iphone-simply-1/