Question

Take for example NSMutableArray:

NSMutableArray* a1 = [[NSMutableArray alloc] initWithCapacity:10];
NSMutableArray* a2 = [NSMutableArray arrayWithCapacity:10];

Under manual reference counting, the second line returned an autoreleased object. Now with ARC enabled, does the second return an __autoreleasing object and the other does not? What's the difference, if any?

What if the class I'm initializing is a custom class which has been converted to ARC, where the conversion removed the autorelease message from the initializer:

MyClass b1 = [[MyClass alloc] initWithNumber:1];
MyClass b2 = [MyClass myClassWithNumber:1];

// MyClass implementation of myClassWithNumber
+(id) myClassWithNumber:(int)num
{
    return [[self alloc] initWithNumber:num];
}

Is there any difference between b1 and b2, and is it any different from how a1 and a2 are created?

Was it helpful?

Solution

LearnCocos2D,

ARC does not change calling conventions. If your method's name would return an autoreleased object under MRR, then it will return one under ARC. ARC is a local optimization to each method. That is why you can mix and match MRR and ARC code in the same project. (Even categories can have different memory management methods.)

In your second code example, ARC adds an autorelease to the returned value, if called for. Why is it the last thing? Because ARC is partially about minimizing your memory footprint. Hence, it wants to manage the lifetime of every object created in the method. The only object created in the method that will ever be autoreleased is the returned value.

In general, ARC is supposed to be minimally invasive to your code. Basically, you are turning over responsibility for memory management to the compiler. (Where it always should have resided anyway.) Problems with ARC surface with bringing toll-free bridged CF objects into Objective-C code. Most times the toll-free bridged items are handled with the __bridged storage modifier. Apple's documentation is quite good around ARC. The Clang documentation is precise.

Don't sweat ARC. As is the case with modern compilers, it will probably manage memory better than you do.

Andrew

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top