NSError的組成
NSError主要由3部分內容組成:
1.Error Domains:在文件NSError.h中定義,包含:
NSMachErrorDomain
NSPOSIXErrorDomain
NSOSStatusErrorDomain
NSCocoaErrorDomain
2.Error Codes:在以下三個文件中定義
<Foundation/FoundationErrors.h> Generic Foundation error codes <AppKit/AppKitErrors.h> Generic Application Kit error codes <CoreData/CoreDataErrors.h> Core Data error codes
3.User Info:這個用戶信息字典包含了NSError本地化后的信息
Error description: User info key: NSLocalizedDescriptionKey Method: localizedDescription (never returns nil) Failure reason: User info key: NSLocalizedFailureReasonErrorKey Method:localizedFailureReason (can return nil) Recovery suggestion: User info key: NSLocalizedRecoverySuggestionErrorKey Method: localizedRecoverySuggestion (can return nil) Recovery options: User info key: NSLocalizedRecoveryOptionsErrorKey Method: localizedRecoveryOptions (if returns nil, implies a single “OK button)
使用和創建NSError
許多Cocoa和Cocoa Touch方法調用時需要傳入一個引用的NSError對象,example:
NSError *theError; BOOL success = [myDoc writeToURL:[self docURL] ofType:@"html" error:&theError]; if (success == NO) { // Maybe try to determine cause of error and recover first. NSAlert *theAlert = [NSAlert alertWithError:theError]; [theAlert runModal]; // Ignore return value. }
顯示NSError信息可以直接使用本地化的NSError信息或是更具Error Domain和Error Code來定制Error信息,example:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { NSString *titleString = @"Error Loading Page"; NSString *messageString = [error localizedDescription]; NSString *moreString = [error localizedFailureReason] ? [error localizedFailureReason] : NSLocalizedString(@"Try typing the URL again.", nil); messageString = [NSString stringWithFormat:@"%@. %@", messageString, moreString]; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:titleString message:messageString delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [alertView show]; } or - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { NSString *errorMsg; if ([[error domain] isEqualToString:NSURLErrorDomain]) { switch ([error code]) { case NSURLErrorCannotFindHost: errorMsg = NSLocalizedString(@"Cannot find specified host. Retype URL.", nil); break; case NSURLErrorCannotConnectToHost: errorMsg = NSLocalizedString(@"Cannot connect to specified host. Server may be down.", nil); break; case NSURLErrorNotConnectedToInternet: errorMsg = NSLocalizedString(@"Cannot connect to the internet.Service may not be available.", nil); break; default: errorMsg = [error localizedDescription]; break; } } else { errorMsg = [error localizedDescription]; } UIAlertView *av = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error Loading Page", nil) message:errorMsg delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [av show];
}
創建返回自定義的NSError:
- (NSString *)fooFromPath:(NSString *)path error:(NSError **)anError { const char *fileRep = [path fileSystemRepresentation]; int fd = open(fileRep, O_RDWR|O_NONBLOCK, 0); if (fd == -1) { if (anError != NULL) { NSString *description; NSDictionary *uDict; int errCode; if (errno == ENOENT) { description = NSLocalizedString(@"No file or directory at requested location", @""); errCode = MyCustomNoFileError; } else if (errno == EIO) { // Continue for each possible POSIX error... } // Create the underlying error. NSError *underlyingError = [[NSError alloc] initWithDomain:NSPOSIXErrorDomain code:errno userInfo:nil]; // Create and return the custom domain error. NSDictionary *errorDictionary = @{ NSLocalizedDescriptionKey : description, NSUnderlyingErrorKey : underlyingError,
NSFilePathErrorKey : path *anError = [[NSError alloc] initWithDomain:MyCustomErrorDomain code:errCode userInfo:errorDictionary]; } return nil;
} // ...
NSError和NSException的區別
iOS官方文檔原文描述如下
Exceptions (represented by NSException objects) are for programming errors, such as an array index that is out of bounds or an invalid method argument. User-level errors (represented by NSError objects) are for runtime errors, such as when a file cannot be found or a string in a certain encoding cannot be read. Conditions giving rise to exceptions are due to programming errors; you should deal with these errors before you ship a product. Runtime errors can always occur, and you should communicate these (via NSError objects) to the user in as much detail as is required.