Skip to content

Instantly share code, notes, and snippets.

@trfiladelfo
Forked from benvium/errors.m
Created July 26, 2016 18:54
Show Gist options
  • Select an option

  • Save trfiladelfo/38c7eca8ac6d24860ef7a10988058353 to your computer and use it in GitHub Desktop.

Select an option

Save trfiladelfo/38c7eca8ac6d24860ef7a10988058353 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] );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment