The mix of Arc and non-arc in iOS engineering

Source: Internet
Author: User

Arc and non-arc are used simultaneously in a project,

1, select the targets in the project, select the target you want to manipulate,
2, choose Build phases, in which Complie sources select the file that needs arc double-click, and enter in the input box:-FOBJC-ARC, if not arc input:-fno-objc-arc

mixed with no problem, no use of the ARC code to continue to insist who apply who released the good. The previous library did not have time to rewrite it, all in this way.

And I don't know what you're using. Third-party code, in general, there are few arc-only code, most of which use some macros to allow the code to adapt to both arc and non-arc (as in # __has_feature (OBJC_ARC)). If you have a small amount of code, consider rewriting yourself

What is arc?

ARC is a new feature of iOS 5, called arc (Automatic Reference counting). Simply put, it is the code that automatically joins the Retain/release, and the code that originally needed to manually add a reference count to handle memory management can be automatically completed by the compiler.

This function is started in IOS 5/mac OS X 10.7 and can be used with Xcode4.2. The simple understanding of arc is that by specifying the syntax, the compiler (LLVM 3.0) automatically generates the reference count of the instance when the code is compiled to manage part of the code. At one point, arc is not a GC, it is just a static analyzer tool of code.

ARC is a new feature of compiler LLVM 3.0, not iOS, so arc supports MAC OS X v10.6 v10.7 (64-bit applications) and iOS 4 iOS 5. (Unfortunately, weak reference is the runtime property and therefore does not support IOS 4 and Mac OS X v10.6.) )

You can't use a variable that starts with new

ARC works only on Objective-c objects, and for core Foundation you still need to manually release them.

Advantages of Arc:
1, no longer need to consider the issue of retain, release, we can consider the issue at a higher level, rather than tangled in the details of when to release.
2, Zeroing-weak Reference, we can finally get rid of the annoying zombies object, think about delegate mechanism, when delegate object deallocated, you send a message to it what happens? Now when you call Self.delegate, if it is released, the weak pointer will automatically become nil.
3, the arc gives the person the feeling is the direct storage object to the variable inside. So the previous piece of impossible code now becomes possible:

Change Point

With a small piece of code, let's look at the point of change before and after 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 the memory management rules in objective-c, we often used the following guidelines

When generating an object, use the Autorelease

When the object is autorelease, first retain

When an object returns in a function, use return [[object retain] autorelease];

With arc, we don't need to do this, even the most basic release.

Benefits of using Arc

What are the benefits of using arc?

As you can see from the example above, it's easier to write objective-c code later, because we don't have to worry about annoying memory management and worrying about memory leaks.

The amount of code has become less, looks refreshed, and saves Labor.

Code is high-speed, reducing the likelihood of inefficient code by using the compiler to manage reference counts

Bad place.

Remember a bunch of new arc rules-keywords and features that require a certain learning cycle

Some old code, third-party code is more troublesome to use, modify the code requires work, or modify the compilation switch

On the 2nd, because the default arc in XCode4.2 is the state of on, there are often "Automatic Reference counting Issue" error messages when compiling old code.

At this point, you can set the "Objectice-c Auto Reference counteting" in the project compilation settings to No. as shown below.

If you only want to do not fit an. m file to arc, you can only add-fno-objc-arc to the file with the flags, such as.

ARC Basic Rules

Retain, release, Autorelease, dealloc are automatically inserted by the compiler and cannot be called in code

Dealloc can be overloaded, but cannot be called [Super Dealloc]

Since ARC is not a GC and requires some rules to allow the compiler to support code insertion, it is important to be clear about these rules before you can write robust code.

Objective-c Object

Objects in Objectivec, with strong references (strong reference) and weak references (Weak reference), require retain to ensure object reference count plus 1 when other objects need to be persisted. As long as the object's holder (owner) exists, the object's strong references persist.

The basic rules for object handling are

This object can be used as long as the object's holder exists (the object is strongly referenced).

When the object loses its holder, it is abandoned.

Strong references (strong reference)

(S1) FirstName as the original holder of the "Natsu" string object, is the strong reference of the NSString type object.
(S2) FirstName into aname here, that is, Aname also becomes the holder of the @ "Natsu" string object, Aname is also strong reference for that object.
(S3) Here, change the contents of FirstName. Generates a new string object "Maki". At this time FirstName become "maki" holders, and @ "Natsu" holders only aname. Each string object has its own owner, so they all exist in memory.
(S4) Appends a new variable othername, which will become another holder of the @ "Maki" object. That is, the strong reference of the NSString type object.
(s5) substituting othername into Aname, the aname will be the holder of the @ "Maki" string object. And the object @ "Natsu" has no owner, the object will be broken.
Weak references (Weak reference)

(W1) In the same way as a strong reference, FirstName exists as the holder of the string Object @ "Natsu". That is, the strong reference of the NSString type object.

(w2) Use the keyword __weak to declare a weak reference weakname variable and firstname into it. At this time weakname although reference @ "Natsu", but 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 holder, while the object @ "Natsu" is abandoned because there is no holder. At the same time, the Weakname variable is automatically replaced with nil.
Reference keywords

Reference references to objects in arc, mainly with the following keywords. With strong, weak, autoreleasing-qualified variables are implicitly initialized to nil.

__strong

The variable declaration defaults to the __strong keyword, and if the variable does not write a keyword, then the default is a strong reference.

__weak

As seen above, this is a weak reference keyword. The concept is a new feature that starts importing from IOS 5/mac OS X 10.7. Because this type does not affect the life cycle of an object, if the object has no previous holder, there is a problem that has just been 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 build setting OS version Deployment Target is set to this lower version, then the compile time will be an error (the current Deployment Target does not support automated __weak reference s), this time, we can use the following __unsafe_unretained.

A weak reference also has a feature that when a parameter object loses its owner, the variable is automatically paid nil (zeroing).

__unsafe_unretained

The keyword, like __weak, is also a weak reference, and the difference from __weak is simply whether to perform a nil assignment (zeroing). However, it is important to note that the object that the variable refers to has been broken, the address still exists, but the object in memory is gone. If you still access the object, it will cause a "bad_access" error.

__autoreleasing

The keyword makes the pair like a deferred release. For example, if you want to pass an uninitialized pair-like reference to a method that instantiates this pair of images in this method, you can use __autoreleasing. He is often used to deal with the return of function-valued parameters, such as 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);}

Again, if the return value of a function is requested in a function, the following code is often expected when the release is on the caller's side.

-(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 parameter of the method is id* and you want the object to be autoreleased when the method returns.

Summarize

Today, we see the basic ARC usage rules

The code cannot use retain, release, retain, Autorelease

Do not overload dealloc (the function can be overloaded if it is disposed of outside the object's memory, but cannot be called [Super Dealloc])

Cannot use Nsallocateobject, Nsdeallocateobject

Object pointers cannot be used in C struct bodies

Between ID and void * If cast requires a specific method (__bridge keyword)

Cannot use NSAutoreleasePool, but requires @autoreleasepool block

You cannot use the name of a property that starts with "new" (If you use the following compilation error "Properties ' s synthesized getter follows COCOA naming convention for returning ' owned ' OBJEC TS ")

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

Arc-to-non-arc blending in iOS engineering

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.