What is arc? Ios5, xcode 4.2

Source: Internet
Author: User

From http://www.yifeiyang.net/development-of-the-iphone-simply-1/

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, it isCodeRetain/release is automatically added. 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.

1234567891011121314151617181920
 @ 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 
123456789101112131415
  @ 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)

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.

12
Nsstring _ weak * string = [[NsstringAlloc] initwithformat :@"First name: % @",[SelfFirstname]; nslog (@"String: % @", String );//String is empty.

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.

1234567891011
-(Void)Generateerrorinvariable:( _ Autoreleasing nserror **)Paramerror{... * Paramerror = [[NserrorAlloc] initwithdomain :@"MyApp"Code: 1 userinfo: errordictionary];}... {Nserror*Error=Nil;[SelfGenerateerrorinvariable: & 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.

123456789101112131415
-(Nsstring*)Stringtest{Nsstring*Retstr= [NsstringStringwithstring :@"Test"];Return[[Retstr retain] autorelease];}//Use arc-(Nsstring*)Stringtest{_ Autoreleasing nsstring * retstr = [NsstringAlloc] initwithstring :@"Test"];ReturnRetstr ;}

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

In the future, we will go deeper into Arc and learn more about its features.

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.