Introduction to ARC and the combination of ARC and non-ARC in the project

Source: Internet
Author: User

Both ARC and non-ARC are used in a project,

1. select Targets in the project and select the Target you want to operate on,
2. Select Build Phases. In Complie Sources, double-click the file to which the ARC is required, and enter-fobjc-arc in the input box. If no ARC is required, enter: -fno-objc-arc

There is no problem with mixing. It is good to continue to insist on who applies for and who releases the code without using the ARC. This method is used when the previous library does not have time to override.

I don't know what third-party code you are using. Generally, there is very little arc only code, most of them use some macros to make the code adapt to both arc and non-arc (determined by # if _ has_feature (objc_arc ). If the amount of code is small, you can rewrite it yourself.

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.

ARC is a new function of the compiler LLVM 3.0, rather than iOS. Therefore, ARC supports Mac OS X v10.6 v10.7 (64-bit applications) and iOS 4 iOS 5. (unfortunately, weak reference is the runtime attribute and therefore does not support iOS 4 and Mac OS X v10.6 .)

You cannot use variables starting with new.

ARC only works for objective-c objects. For Core Foundation and other objects, you still need to manually release them.

Advantages of ARC:
1. We no longer need to consider retain and release. We can consider the issue at a higher level, rather than worrying about the release details.
2. zeroing-weak reference. We can finally get rid of the annoying zombies object and think about the delegate mechanism. After the delegate object deallocated, what will happen if you send a message to it? Now when you call self. delegate, if it is released, the weak pointer will automatically become nil.
3. ARC stores objects directly into variables. Therefore, the previous piece of impossible code is now possible:

 

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

 

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) firstName is the initial holder of the "natsu" String object and 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 will become the owner of the @ "maki" String object. The object @ "natsu" has no owner, and the object will be discarded.
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.

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 ).

 

 

_ 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.

- (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.

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 ")

 

Part 1:
Http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1
Part 2:
Http://www.raywenderlich.com/5773/beginning-arc-in-ios-5-tutorial-part-2

Apple documentation
Http://developer.apple.com/library/IOs/#releasenotes/ObjectiveC/RN-TransitioningToARC/_index.html

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.