17

我想从中获得一些有用的信息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

4 回答 4

28

最后,我遵循完美 NSError 打印的代码。感谢@jbat100 和@Peter Warbo,我在他们身上加了一点代码:

    NSDictionary *userInfo = [error userInfo];
    NSString *errorString = [[userInfo objectForKey:NSUnderlyingErrorKey] localizedDescription];
于 2012-06-15T09:45:40.017 回答
1

怎么样:

NSDictionary *userInfo = [error userInfo];
NSString *error = [userInfo objectForKey:@"NSUnderlyingError"];
NSLog(@"The error is: %@", error);
于 2012-06-14T08:07:04.413 回答
1

如果你查看NSError 文档,它有一个User info dictionary keys部分,其中有一个定义为 NSUnderlyingErrorKey 的常量(它也有键的描述)。

NSDictionary *userInfo = [error userInfo];
NSError *underlyingError = [userInfo objectForKey:NSUnderlyingErrorKey];
NSString *underlyingErrorDescription = [underlyingError localizedDescription];
于 2012-06-14T08:19:42.693 回答
1

本地化恢复建议非常有用。您可以从中获取 JSON 字符串:

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

            NSError *aerror = nil;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData: [JSON dataUsingEncoding:NSUTF8StringEncoding]
                                                                 options: NSJSONReadingMutableContainers
                                                                   error: &aerror];
于 2014-10-01T10:58:37.480 回答