Wednesday, 25 July 2012

The correct way to use your own NSError objects in your app

// 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] );
}
}
view raw errors.m hosted with ❤ by GitHub
Thanks to Mike Abdullah @mikeabdullah for pointing out the 'deliberate' (ahem) mistake in this post the first time around. Oops.

No comments:

Post a Comment