Correct Structure to check for Errors using NSError
cocoa, error-handling, objective-c, oop
Solution
I think that none of the answers presented here are taking into account Apple's recommended practices.
Basically you should never check for the `NSError` object to determine if there was a problem. You check if there was a problem by checking the value returned from the method that takes a pointer to a pointer to an `NSError`.
From the Apple documentation:
Important Success or failure is indicated by the return value of the method. Although Cocoa methods that indirectly return error objects in the Cocoa error domain are guaranteed to return such objects if the method indicates failure by directly returning `nil` or `NO`, you should always check that the return value is `nil` or `NO` before attempting to do anything with the `NSError` object.
Problem
I'm coding up various routines and I'm trying my best to keep it neat and refactored. Methods I'm creating are starting to look similar to this code: ``` -(IBAction)buttonPress:(id)sender { // Create Document Shopping List with this document [self doSomething:&error]; if(error) { [NSApp presentError:&error]; return nil; } [self doSomethingElse:&error]; if(error) { [NSApp presentError:&error]; return nil; } [self doYetSomethingElse:&error]; if(error) { [NSApp presentError:&error]; return nil; } } ``` I love NSError, but this seems like an awfully clumsy way of handling all my errors. A few thoughts I've had about alternative ways: a) the error checking could be built into the methods doSomething, doSomethingElse etc, but then I wouldn't be able to exit the button press method without doing some kind of checking on the return value, which would lead me back to a similar structure. b) I could set up the NSError as being Key Value Observed, but something about this feels deeply wrong. I'm very aware of the possibilities of abuse with KVO, so I'm trying to do everything without it whereever possible. Surely I'm missing something really basic here? Is there a pattern that can help me? Or is this structure OK?