Created
August 17, 2012 10:09
-
-
Save benvium/3377684 to your computer and use it in GitHub Desktop.
The correct way to use NSError objects in your Objective-C Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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] ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is incorrect and prone to crashing. What happens when I pass in NULL instead of an NSError **? You need to say: