Introduction of ARC and mixing of ARC and non ARC in Engineering

ARCUsed in conjunction with non ARC in a project.

1,Select the Targets in the project and select the Target you want to operate.
2,Select Build Phases, double-click the file that requires ARC in Complie Sources, and enter: – fobjc – arc in the input box, and – fno – objc – arc if you don’t want ARC

There is no problem with mixing. It doesn’t matter if ARC code continues to insist on who will apply for release. Previous libraries did not have time to rewrite.

And I don’t know what third-party code you’re using. Generally speaking, there’s very little arc only code right now. Most of it uses macros to make the code fit both arc and non-arc (with # if has _feature (objc_arc)).If the amount of code is small, you can consider yourself rewriting.

ARCWhat is it?

ARCIt is the new function launched by iOS 5, and its full name is ARC (Automatic Reference Counting). Simply put, retain / release is automatically added to the code, which was originally added manually to handle memory management QuotesThe counting code can be automatically completed by the compiler.

The function was imported from iOS 5/ Mac OS X 10.7, using Xcode4.2You can use this function. To understand ARC simply is to let the compiler (LLVM) through the specified syntax.3) automatically generate instances when compiling code.Reference count management part of the code. One thing, ARC is not GC, it is just a static analysis of code (StaticAnalyzer) tools.

ARCIt’s a compilerLLVM 3.0ANew function instead of iOS, so ARC support. Mac OS X v10.6 v10.7 (64-bit applications) And iOS 4 iOS 5. (Unfortunately, weak reference is a runtime attribute, so iOS 4 and iOS 5 are not supportedMac OS X v10.6。

You can’t use the variables that new starts with.

ARCIt works only on Objective-C objects, and for Core Foundation and the like, you still need to release it manually.

ARCAdvantages:
1、Instead of thinking about retain and release, we can think about it at a higher level, not about the details of when to release it.
2、zeroing-weak reference , We can finally get rid of the annoying.zombies Object, think about the delegate mechanism when delegate objects.deallocatedAfter that, what happens if you send a message to it again? Now when you call self. delegate, if it is released, the weak pointer automatically becomes nil.
3、ARCThe feeling is to store objects directly into variables. Therefore, a previous piece of impossible code is now possible.

 

Change point

Through a small piece of code, let’s look at the change points 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 the memory management rule in Objective-C, we often use the following criteria.

   When generating objects, use autorelease

   When the object is substituted, it will be autorelease first and then retain.

   When objects are returned in function, use return [[object retain] autorelease];

After using ARC, we don’t need to do this. Even the most basic release is not needed.

 

Benefits of using ARC

   What are the advantages of using ARC?

   As you can see from the examples above, it’s much easier to write Objective-C code because we don’t have to worry about annoying memory management and memory leaks.

   The total amount of code has been reduced. It looks a lot fresher and saves labor.

   High speed code reduces the possibility of inefficient code by using compiler to manage reference counting.

 

A bad place

   Remember that a bunch of new ARC rules – keywords and features need a certain learning cycle.

   Some old code is troublesome to use with third-party code; modifying the code requires labor, or modifying the compilation switch

On the second point, since the default ARC in XCode 4.2 is the state of ON, there is often an error message “Automatic Reference Counting Issue” when compiling old code.

 

At this point, you can set the “Objectice-C Auto Reference Counting” in the project compilation settings to NO. As shown below.

 

If you want to only adapt to A. m file that does not fit ARC, you can compile FLAGS for that file only by adding – fno – objc – arc, as shown below.

 

 

ARCBasic rules

    retain, release, autorelease, deallocAutomatically inserted by the compiler and cannot be invoked in the code.

    deallocAlthough it can be overloaded, it can not call [super dealloc].

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

 

Objective-Cobject

 

ObjectiveCThere are Strong Reference and Weak Reference, and when you need to keep other objects, you need to retain to make sure the object reference count is 1. The object holder (owner) exists as long as it exists.Then the strong reference of the object always exists.

 

The basic rule of object handling is

 

  As long as the object holder exists (the object is strongly referenced), you can use the object.

    When the object loses its holder, it is destroyed.

 

Strong reference (Strong reference)

(s1)firstNameAs the initial holder of the “natsu” string object, it is the Strong reference of the NSString type object.
(s2)Here, first Name is substituted in aName, which means that aName becomes the holder of the @”natsu” string object, for which aName is also a Strong reference.
(s3)Here, change the content of firstName. Generate a new string object “maki”. At that time, firstName became the holder of Maki, while the holder of @ Natsu had only aName. Each string object has its own holder, so they have their own holders.Both 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)When otherName is substituted into aName, aName will become the holder of the @ maki ‘string object. The object @ Natsu has no owner, and the object will be abandoned.
Weak reference (Weak reference)

(w1)As with strong reference, firstName is the holder of string object @ “Natsu”. That is the Strong reference of the NSString type object.

(w2)Use keyword __weak to declare weak reference weakName variable and replace firstName. At this time, although weakName reference “Natsu”, but still Weak reference. That is, weakName can see @ @ Na.TSU “, but not its holder.
(w3)firstNamePointing to the new object @ “maki” becomes its holder, while the object @”Natsu”is abandoned because it has no holder. At the same time, weakName variables will be automatically replaced by nil.
Reference keywords

ARCReferencing references to objects, with the following key words. Variables that are defined by strong, weak, and autoreleasing are implicitly initialized to nil.

__strong

Variable declarations default to the strong keyword, and if the variable does not write any keywords, the default is a strong reference.

__weak

As you can see above, this is a weak reference keyword. The concept is new, and is imported 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, then the problem of just creating it is brokenFor example, the following code.

NSString __weak *string = [[NSString alloc] initWithFormat:@"First Name: %@", [self firstName]];
NSLog(@"string: %@", string); //At this point, string is empty.

If the compile settings OS version Deployment Target is set to this lower version, the current deployment target does not support autoMated __weak references) at this time, we can use the __unsafe_unretained below.

Weak reference also has a feature that when the parameter object loses its owner, the variable is automatically paid to nil (Zeroing).

 

 

__unsafe_unretained

The keyword, like u weak, is also a weak reference, and the difference between u weak and u weak is whether to perform nil assignment (Zeroing). However, it is important to note that the object the variable refers to has been corrupted, that the address still exists, and that the object in memory is gone. If you still visit thisThe object will cause the “BAD_ACCESS” error.

__autoreleasing

This keyword makes the image delay release. For example, if you want to pass an uninitialized object reference to a method in which the object is instantiated, you can use u autoreleasing. He is often used for processing 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);
}

Also, if the return value of a function is applied in the function, the code that you want to release is often the following at the calling end.

-(NSString *)stringTest
{
    NSString *retStr = [NSString stringWithString:@"test"];

    return [[retStr retain] autorelease];
}
// Using 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 expected to return.

 

summary

Today, we see the basic ARC usage rules.

    Retain, release, retain, autorelease can not be used in code.

    Do not overload dealloc (you can overload this function if you are dealing with something outside of the object’s memory, but you can’t call [super dealloc])

    Cannot use NSAllocateObject, NSDeallocateObject

    Object pointer cannot be used in C structure

    idIf there is a cast between void *, you need to use a specific method (__bridge keyword).

    You cannot use NSAutoReleasePool, but you need @autoreleasepool blocks.

    You can’t use the property name starting with “new” (if you use it, there will be the following compilation error) Property’s synthesized getter follows Cocoa naming convention for reTurning ‘owned’ 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 File
http://developer.apple.com/library/IOs/#releasenotes/ObjectiveC/RN-TransitioningToARC/_index.html

Leave a Reply

Your email address will not be published. Required fields are marked *