Question

-(NSData *)jsonRepresentation:(NSError **error)error {
   NSDictionary *dict = [self getDictRepresentation];
   return [NSJSONSerialization dataWithJSONObject:dict options:nil error:error];
}

// Some other place...

NSError *__autoreleasing error = nil;
NSData *json = [obj jsonRepresentation:&error];

Do autoreleasing semantics safely convey error up the stack to my second code block?

Était-ce utile?

La solution 2

Yes, it's correct, but you should specify this modifier in the method declaration, and not in the declaration of the variable. Even the official documentation of Apple mentions this very situation explicitly:

__autoreleasing is used to denote arguments that are passed by reference (id *) and are autoreleased on return.

Autres conseils

As per the clang ARC spec, a method argument of the form NSError ** (or rather, a pointer to any obj-c object) is implicitly assumed to be NSError * __autoreleasing *. This means that the error will be autoreleased in the method.

As for the call site, if you call it with an __autoreleasing variable, as you have, then everything is just fine. In fact, I recommend this pattern. However, it will still work if you call it with a __strong variable instead. In that case, the compiler will generate an unnamed __autoreleasing temporary, pass the address of that to the method, and then upon return, it will assign the temporary into the __strong. So if you have

NSError *foo;
[bar callMethodWithError:&foo];

the compiler will treat this the same as

NSError *foo;
NSError * __autoreleasing tmp = foo;
[bar callMethodWithError:&tmp];
foo = tmp;

It's actually slightly more complicated than that if the out-param is marked out, but this is generally how it works.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top