如何从NSError获取更多有用信息?

时间:2012-06-14 07:53:49

标签: ios nserror

我想从NSError获取一些有用的信息。 如果我打印出[error userInfo],我会得到以下内容:

{
    NSFilePath = "/Users/apple/Library/Application Support/iPhone Simulator/5.1/Applications/08260B6A-4D65-48DF-ADD1-FFC8750081E8/Documents/abc";
    NSUnderlyingError = "Error Domain=NSPOSIXErrorDomain Code=17 \"The operation couldn\U2019t be completed. File exists\"";
}

我想显示最后一行:“文件存在”,但我怎么能把它拿出来?

我试过了:

localizedDescription
localizedFailureReason
localizedRecoverySuggestion
localizedRecoveryOptions
recoveryAttempter

非他们显示“文件存在”。

4 个答案:

答案 0 :(得分:24)

最后,我按照代码进行完美的NSError打印。 谢谢@ jbat100和@Peter Warbo,我在它们上添加了一些代码:

    NSDictionary *userInfo = [error userInfo];
    NSString *errorString = [[userInfo objectForKey:NSUnderlyingErrorKey] localizedDescription];

答案 1 :(得分:1)

怎么样:

NSDictionary *userInfo = [error userInfo];
NSString *error = [userInfo objectForKey:@"NSUnderlyingError"];
NSLog(@"The error is: %@", error);

答案 2 :(得分:1)

如果你查找NSError documentation,它有一个User info dictionary keys部分,其常量定义为NSUnderlyingErrorKey(它还有一个关键字的描述)。

NSDictionary *userInfo = [error userInfo];
NSError *underlyingError = [userInfo objectForKey:NSUnderlyingErrorKey];
NSString *underlyingErrorDescription = [underlyingError localizedDescription];

答案 3 :(得分:1)

localizedRecoverySuggestion非常有用。 您可以从中获取JSON字符串:

NSString *JSON = [[error userInfo] valueForKey:NSLocalizedRecoverySuggestionErrorKey] ;

            NSError *aerror = nil;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData: [JSON dataUsingEncoding:NSUTF8StringEncoding]
                                                                 options: NSJSONReadingMutableContainers
                                                                   error: &aerror];
相关问题