2

Possible Duplicate:
Objective-C: With ARC, what's better? alloc or autorelease initializers?

Does ARC automatically turn the autoreleased versions of class initializers into the appropriate non-autorelased versions, or are they still technically being autoreleased?

I don't want to keep memory around any longer than it's absolutely required, so I've gotten in the habit of using alloc/init in almost all circumstances. Now in ARC, I'm wondering if I can just start using the "autorelease" initializers and expect them to act like a non-autorelased versions would behave...

Does anyone have any documentation on where I can find out what happens to autoreleased methods under ARC?

Community
  • 1
  • 1
Mason Cloud
  • 1,266
  • 1
  • 15
  • 20
  • The answers to this question - essentially the same - suggests that the autorelease versions are actually faster: http://stackoverflow.com/questions/6776537/objective-c-with-arc-whats-better-alloc-or-autorelease-initializers – Ben Clayton Jun 25 '12 at 17:40

3 Answers3

2

When you get an autoreleased object, ARC will manage to avoid the autorelease pool, as long as both your code and the called method/function are compiled with ARC.

ARC adds a call to objc_retainAutoreleasedReturnValue in your code and a call to objc_autoreleaseReturnValue in the called function/method. At runtime when objc_autoreleaseReturnValue sees that the returned value will be retained by objc_retainAutoreleaseReturnValue, it doesn't autorelease the object and sets a flag to tell objc_retainAutoreleaseReturnValue not to retain the object. Thus you get no (perceptible) extra cost for using a convenient creation method rather that alloc/init.

For more information about that mechanism, you may read How does objc_retainAutoreleasedReturnValue work? by Matt Galloway.

In conclusion, just use the method you prefer, Apple engineers will ensure it runs fast.

Nicolas Bachschmidt
  • 6,475
  • 2
  • 26
  • 36
0

Well technically they're not the same, since ARC simply inserts 'retains' and 'releases' into your code (where necessary) when it's compiled.

lottscarson
  • 578
  • 5
  • 14
0

ARC stores a strong reference to an object if you use a pointer when initiating it, otherwise it deallocs the object immediately. So I believe the answer to your question about NSArray is that no, ARC does not turn it into an autoreleased object. It also adds a release statement to the code whenever the object is no longer needed in a scope:

-(void) aMethod
{
    [NSArray alloc];
}

//in essence is transformed into

-(void) aMethod
{
    NSArray *temp = [NSArray alloc];
    [temp release];
}

If you had stored a pointer, ARC would add a release as soon as the object was about to leave the scope.

Dustin
  • 6,783
  • 4
  • 36
  • 53