Skip to content

Instantly share code, notes, and snippets.

@benvium
Created August 17, 2012 10:09
Show Gist options
  • Save benvium/3377684 to your computer and use it in GitHub Desktop.
Save benvium/3377684 to your computer and use it in GitHub Desktop.
The correct way to use NSError objects in your Objective-C Code
// A function that returns an object or nil if there's an error.
- (NSObject*) doSomethingComplexAndReturnObject:(NSString*) input error:(NSError**) error {
// do some work..
BOOL itWorked = YES;
if (itWorked) {
return [[NSObject alloc] init]; // Do better memory management than this please.
} else {
*error = [NSError errorWithDomain:@"com.mycompany.myapp" code:14 userInfo:[NSDictionary dictionaryWithObject:@"My error message" forKey:NSLocalizedDescriptionKey]];
return nil;
}
}
// This function demonstrates using the function above
- (void) useTheDoSomethingComplexFunction {
NSError* error = nil;
NSObject* ob = [self doSomethingComplexAndReturnObject:@"foobar" error:&error];
if (ob) {
// do the success thing!
} else if (error) {
NSLog(@"Can't do the success thing as we have an error %@", [error localizedDescription] );
}
}
@grosch
Copy link

grosch commented May 8, 2014

This is incorrect and prone to crashing. What happens when I pass in NULL instead of an NSError **? You need to say:

if (error) 
    *error = .....;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment