How to bubble error object across several methods?
This is more of a C question but here it goes.
I've a method that receives as a parameter the address of a pointer to an NS开发者_运维知识库Error object. Now, that method is buried several levels deep in the class hierarchy and I need to make the error object bubble all the way to the top.
I could return the error object on each method but I'd rather do it the Cocoa way and return a boolean while passing the error object as a parameter.
How can I do this?
I could return the error object on each method but I'd rather do it the Cocoa way and return a boolean while passing the error object as a parameter.
The Cocoa way is the Boolean direct return with a by-reference (i.e., through pointer) return of the error value, like so:
NSError *error = nil;
if ([foo trySomething:bar error:&error]) {
//Success!
} else {
//Failure!
}
(Alternatively, trySomething:error:
may return an object, in which case you treat that object as the Boolean return: non-nil
is true/succeeded, nil
is false/failed.)
To make this chainable, each method (except the outermost) should have an error-pointer parameter, and use that in its implementation:
- (void) trySomething:(MyBar *)bar error:(out NSError **)outError
if ([bartender restock:bar error:outError]) {
//Success!
} else {
//Failure!
}
}
You can combine both approaches, catching the error object in your own local variable in order to customize or wrap it in the failure case before storing the customized/wrapper error at the error-return pointer for your caller to receive.
精彩评论