Example: The -save:
method of NSManagedObjectContext
is declared like this:
- (BOOL)save:(NSError **)error
Since NSError is already a class, and passing a pointer would actually have the effect of modifying this object inside the implementation of -save:
, what's the point of passing a pointer to a pointer here? What's the advantage/sense?
Usage example:
NSError *error;
if (![managedObjectContext save:&error]) {
// Handle the error.
}
@Anon is correct. I'll add: This is the Cocoa way to produce errors, in place of throwing exceptions.
In your example, you have:
NSError *error = nil;
if (![managedObjectContext save:&error]) {
// Handle the error.
}
Immediately after the call to save:
, if there was an error, then the save:
method will have created a new NSError
object, and changed your error
variable to point from nil
to the new error object. That way you can examine the NSError
object yourself and respond appropriately to it.
IMO, this is cleaner than throwing an exception (which in my philosophy should only be done when something catastrophic and unrecoverable happens).
It is what some people refer to as an "out" parameter.
You're not passing a pointer to an NSError object, you're passing a pointer to a local variable. This gives the called method the ability to modify your local variable; in this case, to assign it to an NSError instance.
Perhaps what's confusing is that the local variable you're passing to save:
is itself a pointer, so the variable type ends up being a pointer to a pointer.
Bottom line, it's a pointer to a local variable, and it works the same whether the local variable is an int
or an NSError*
.
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