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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With