错误信息 NSError

一、获取系统的错误信息

比如移动文件时,获取文件操作错误:

<span style="background-color: rgb(255, 255, 255);"> <span style="font-size:18px;">   NSError *error =nil;
    [[NSFileManager defaultManager]moveItemAtPath:@"/users"toPath:@"/hh"error:&error];
    if (error) {
        NSLog(@"如果有错误信息,打印错误的本地化描述 error = %@",[error localizedDescription]);
        NSLog(@"11........//%d",[error code]);
        NSLog(@"11。。。%@",[error domain]);
        NSLog(@"11........//%@",[error userInfo]);
        NSLog(@"11localizedFailureReason = %@",[error localizedFailureReason]);
    }</span></span>

2014-04-23 09:14:16.609 Error Demo[428:60b]

如果有错误信息,打印错误的本地化描述 error = The operation couldn’t be completed. (Cocoa error 513.)

2014-04-23 09:14:16.610 Error Demo[428:60b] 11........//513

2014-04-23 09:14:16.611 Error Demo[428:60b] 11。。。NSCocoaErrorDomain

2014-04-23 09:14:16.635 Error Demo[428:60b] 11........//{

    NSDestinationFilePath = "/hh";

    NSFilePath = "/users";

    NSSourceFilePathErrorKey = "/users";

    NSUnderlyingError = "Error Domain=NSPOSIXErrorDomain Code=13 \"The operation couldn\U2019t be completed. Permission denied\"";

    NSUserStringVariant =     (

        Move

    );

}

2014-04-23 09:14:16.635 Error Demo[428:60b] 11localizedFailureReason = (null)

二、自定义错误信息

通常可以通过下面语句,自定义个NSError对象

<span style="background-color: rgb(255, 255, 255);"><span style="font-size:18px;">#define CustomErrorDomain @"com.xiaodao.test"
typedef enum {
    
       XDefultFailed = -1000,
       XRegisterFailed,
       XConnectFailed,
       XNotBindedFailed
    
}CustomErrorFailed;
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"test error"forKey:NSLocalizedDescriptionKey];
    NSError *err2 = [NSError errorWithDomain:CustomErrorDomain code:XRegisterFailed userInfo:userInfo];
    NSLog(@"22 localizedDescription.....%@",[err2 localizedDescription]);
    NSLog(@"22........//%d",[err2 code]);
    NSLog(@"22。。。%@",[err2 domain]);
    NSLog(@"22.....userinfo %@",[err2 userInfo]);</span></span>


2014-04-23 09:14:16.636 Error Demo[428:60b] 22 localizedDescription.....test error

2014-04-23 09:14:16.636 Error Demo[428:60b] 22........//-999

2014-04-23 09:14:16.637 Error Demo[428:60b] 22。。。com.xiaodao.test

2014-04-23 09:14:16.637 Error Demo[428:60b] 22.....userinfo {

    NSLocalizedDescription = "test error";

}

其中,自定义错误域对象CustomErrorDomain,通常用域名反写,也可以是任何其他字符串

code错误标识, 系统的code一般都大于零,自定code可以用枚举(最好用负数, 但不是必须的)

userInfo自定义错误信息,NSLocalizedDescriptionKey是NSError头文件中预定义的键,标识错误的本地化描述

可以通过NSError的localizedDescription方法获得对应的值信息


三、NSError头文件解析

1.NSError对象中,主要有三个私有变量

错误域(NSInteger): _domain

错误标示(NSString *):_code

错误详细信息(NSDictionary *):_userInfo

通常用_domain和_code一起标识一个错误信息


你可能感兴趣的:(错误信息 NSError)