OS X and iOS libraries often have functions that return a BOOL
take some parameters to perform an action and an NSError
pointer. NSManagedObjectContext
does this when fetching for example. There are many other places too. After using these long enough you might start writing your own functions this way too.
- (BOOL)someOperationWithParameter: (NSObject *)p error: (NSError **)error {
//do stuff
if (failed) {
*error = [NSError ...]
return false;
}
}
The code inside the failure block gets repetitive very quickly. Here's a function that makes it better.
- (BOOL)failWithError: (NSError **)error code: (NSInteger)code description: (NSString *) description reason: (NSString *) reason {
*error = [NSError errorWithDomain: @"com.mikeradin.codesample"
code: code
userInfo: @{ NSLocalizedDescriptionKey: description, NSLocalizedFailureReasonErrorKey: reason }];
return false;
}
Now the sample method can fail as follows:
return [self failWithError: error code: -57 description: @"Operation could not be completed." reason: @"User error."];