Peter Lapisu
Peter Lapisu

Reputation: 20975

__autoreleasing in error:(NSError *__autoreleasing *)outError

I noticed this pattern in Apple functions which return errors

error:(NSError *__autoreleasing *)outError

I understand the meaning, that it's pointer to pointer, used to carry out the result (using just * would change only the local copied variable, but not the outside one) but I'm concerned about the:

__autoreleasing

What happens if I leave it out? Do I get a leak? Why is it necessary?

Upvotes: 4

Views: 3414

Answers (1)

Martin R
Martin R

Reputation: 539805

You don't have to explicitly specify __autoreleasing when defining a function that returns an object, for example

-(BOOL)doSomething:(NSError **)error;

The ARC compiler automatically inserts the __autoreleasing. This is explained in the Clang/ARC documentation:

4.4.2 Indirect parameters

If a function or method parameter has type T*, where T is an ownership-unqualified retainable object pointer type, then:

  • if T is const-qualified or Class, then it is implicitly qualified with __unsafe_unretained;
  • otherwise, it is implicitly qualified with __autoreleasing.

The Xcode code completion also knows about that and displays (NSError *__autoreleasing *)error.


When calling such a function the ARC compiler also automatically does "the right thing", so you can just call

NSError *error;
BOOL success = [self doSomething:&error];

As explained in the "Transitioning to ARC Release Notes", the compiler inserts a temporary __autoreleasing variable:

NSError *error;
NSError * __autoreleasing tmp = error;
BOOL success = [self doSomething:&tmp];
error = tmp;

(For the gory details you can read 4.3.4 "Passing to an out parameter by writeback" in the Clang/ARC documentation.)

Upvotes: 8

Related Questions