iOS app development: What is ARC?

Source: Internet
Author: User

iOS app development: What is ARC? Blog Category:
    • Phone/ios/objective-c/Swift

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.

Change Point

With a small piece of code, let's look at the point of change before and after arc.

C code
  1. @interface Nonarcobject:nsobject {
  2. NSString *name;
  3. }
  4. -(ID) Initwithname: (NSString *) name;
  5. @end
  6. @implementation Nonarcobject
  7. -(ID) Initwithname: (NSString *) NewName {
  8. self = [super init];
  9. if (self) {
  10. name = [NewName retain];
  11. }
  12. return self;
  13. }
  14. -(void) Dealloc {
  15. [Name release];
  16. [Super Dealloc];
  17. }
  18. @end

C code
  1. @interface Arcobject:nsobject {
  2. NSString *name;
  3. }
  4. -(ID) Initwithname: (NSString *) name;
  5. @end
  6. @implementation Arcobject
  7. -(ID) Initwithname: (NSString *) NewName {
  8. self = [super init];
  9. if (self) {
  10. name = NewName;
  11. }
  12. return self;
  13. }
  14. @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)

In this case, the FirstName is put into Aname, that is, Aname also becomes the holder of the @ "Natsu" string object, and Aname strong for that object.

(S3)

Here, change the content 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)

Append the 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, 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)

Let's take a look at how weak references (Weak reference) are used.

(W1)

As with strongly referenced methods, FirstName is present as a holder of the string Object @ "Natsu". That is, the strong reference of the NSString type object.

(W2)

Using the keyword __weak, declare the weak reference weakname variable, substituting the FirstName. 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.

C code
    1. NSString __weak *string = [[NSString alloc] initwithformat:@"first Name:%@", [self firstName]];
    2. 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.

C code
    1. -(void) generateerrorinvariable: (__autoreleasing nserror * *) paramerror {
    2. ....
    3. *paramerror = [[Nserror alloc] initwithdomain:@"MyApp" Code:1 userinfo:errordictionary];
    4. }
    5. ....
    6. {
    7. Nserror *error = nil;
    8. [Self generateerrorinvariable:&error];
    9. NSLog (@"error =%@", error);
    10. }

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.

C code
  1. -(NSString *) stringtest
  2. {
  3. NSString *retstr = [nsstring stringwithstring:@"test"];
  4. return [[Retstr retain] autorelease];
  5. }
  6. Using arc
  7. -(NSString *) stringtest
  8. {
  9. __autoreleasing nsstring *retstr = [NSString alloc] initwithstring:@"test"];
  10. return retstr;
  11. }

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

iOS app development: What is ARC?

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.