Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Point of (NSError**)error?

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.
}
like image 503
openfrog Avatar asked Jan 14 '10 21:01

openfrog


2 Answers

@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).

like image 117
Dave DeLong Avatar answered Oct 16 '22 01:10

Dave DeLong


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*.

like image 30
Darren Avatar answered Oct 16 '22 01:10

Darren