NSError *e = nil; [[NSFileManager defaultManager] moveItemAtPath:sourcePath toPath:targetPath error:&e]; if (e) { NSLog(@"move failed:%@", [e localizedDescription]); }先定一个空的错误信息
NSError *e = nil;取地址
&e如果有错误信息,打印错误的本地化描述
if (e) { NSLog(@"move failed:%@", [e localizedDescription]); }二、自定义错误信息
#define CustomErrorDomain @"com.xiaodao.test" typedef enum { XDefultFailed = -1000, XRegisterFailed, XConnectFailed, XNotBindedFailed }CustomErrorFailed; NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"is a error test" forKey:NSLocalizedDescriptionKey]; NSError *aError = [NSError errorWithDomain:CustomErrorDomain code:XDefultFailed userInfo:userInfo];其中,自定义错误域对象CustomErrorDomain,通常用域名反写,也可以是任何其他字符串
- (Bool)doSomething:(NSDictionary *)parameter1 error:(NSError **)aError { //TODO: do something *aError = [NSError errorWithDomain:CustomErrorDomain code:XDefultFailed userInfo:userInfo]; return Yes; }三、NSError头文件解析
NSString *const NSPOSIXErrorDomain; NSString *const NSOSStatusErrorDomain; NSString *const NSMachErrorDomain;3.预定义的userinfo键名
NSString *const NSLocalizedDescriptionKey;取方法
- (NSString *)localizedDescription;失败原因键
NSString *const NSLocalizedFailureReasonErrorKey取方法
- (NSString *)localizedFailureReason;恢复建议键
NSString *const NSLocalizedRecoverySuggestionErrorKey;取方法
- (NSString *)localizedRecoverySuggestion;恢复选项键
NSString *const NSLocalizedRecoveryOptionsErrorKey取方法
- (NSArray *)localizedRecoveryOptions;其他键
NSString *const NSRecoveryAttempterErrorKey; NSString *const NSHelpAnchorErrorKey; NSString *const NSStringEncodingErrorKey ; NSString *const NSURLErrorKey; NSString *const NSFilePathErrorKey;用法:
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:@"这是错误详细的描述信息", NSLocalizedDescriptionKey, error, NSUnderlyingErrorKey, nil]];
4.主要的初始化方法:
- (id)initWithDomain:(NSString *)domain code:(NSInteger)code userInfo:(NSDictionary *)dict; + (id)errorWithDomain:(NSString *)domain code:(NSInteger)code userInfo:(NSDictionary *)dict;