Reading — step 1 of 5
Learn
Cocoa's convention: methods that can fail return a primary value (BOOL or object) and take an NSError ** out-parameter.
NSError *err = nil;
NSString *contents = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&err];
if (!contents) {
NSLog(@"failed: %@", err.localizedDescription);
} else {
use(contents);
}
The &err is an out-parameter. If the method fails, it sets *err to an NSError; if it succeeds, error is left alone (often nil).
Convention:
- Return
nil(for object returns) orNO(for BOOL returns) on failure - Set
*erroronly if non-NULL and only on failure - Don't set error on success
Constructing your own NSError:
NSError *err = [NSError errorWithDomain:@"com.example.MyApp"
code:404
userInfo:@{NSLocalizedDescriptionKey: @"not found"}];
Why not just throw? Objective-C does have @throw and @try/@catch, but Cocoa convention reserves them for unrecoverable bugs only (programmer errors). For everything users could reasonably handle, return-value + NSError is the pattern.
Defining a method that takes NSError:
- (NSData *)loadDataFromURL:(NSURL *)url error:(NSError * _Nullable * _Nullable)error;
The _Nullable * _Nullable means "the pointer can be null AND what it points to can be nil." Common idiom — the caller might pass NULL if they don't care about the error.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…