如何在Xcode控制台中漂亮打印NSError对象?

时间:2011-08-24 07:15:56

标签: ios xcode cocoa macos debugging

我在Xcode控制台中打印了一个NSError对象(通过NSLog(@"%@", error);),对于某种错误,这就是我得到的:

Domain=NSCocoaErrorDomain Code=133020 "The operation couldn’t be completed. (Cocoa error 133020.)" UserInfo=0xe939170 {conflictList=(
    "NSMergeConflict (0xe93cad0) for NSManagedObject (0x5dba970) with objectID '0x5dc26f0 <x-coredata://775D53AE-58A4-4B18-BA52-D46781A183AE/SomeObject/p1>' with oldVersion = 2 and newVersion = 3 and old object snapshot = {\n    creationDate = \"2011-08-24 06:52:22 +0000\";\n    prop1 = \"a65e349a-b315-488e-b7f8-e459e353fd6e\";\n    username = \"test-user\";\n    password = \"foobar\";\n} and new cached row = {\n    creationDate = \"2011-08-24 06:52:22 +0000\";\n    prop1 = \"a65e349a-b315-488e-b7f8-e459e353fd6e\";\n    username = \"test-user\";\n    password = \"foobar\";\n}"

当我用换行符替换所有'\ n'和换行符中的所有\'s时,我得到一个格式很好的错误信息:

Domain=NSCocoaErrorDomain Code=133020 "The operation couldn’t be completed. (Cocoa error 133020.)" UserInfo=0xe939170 {conflictList=(
    "NSMergeConflict (0xe93cad0) for NSManagedObject (0x5dba970) with objectID '0x5dc26f0 <x-coredata://775D53AE-58A4-4B18-BA52-D46781A183AE/SomeObject/p1>' with oldVersion = 2 and newVersion = 3 and old object snapshot = {
    creationDate = "2011-08-24 06:52:22 +0000";
    prop1 = "a65e349a-b315-488e-b7f8-e459e353fd6e";
    username = "test-user";
    password = "foobar";
} and new cached row = {
    creationDate = "2011-08-24 06:52:22 +0000";
    prop1 = "a65e349a-b315-488e-b7f8-e459e353fd6e";
    username = "test-user";
    password = "foobar";
}"

我更希望在Xcode本身看到这个格式正确的错误消息,而不是在另一个编辑器中复制粘贴它和搜索和替换字符。有没有办法做到这一点?

编辑为清楚起见,错误是由核心数据保存操作生成的:

NSError *error
if (![context save:&error]) {
    NSLog(@"%@", error);
}

在这种情况下,错误对象的违规部分(从中打印\ n和\的s)是错误的conflictList字典中userInfo键的值。

2 个答案:

答案 0 :(得分:9)

userInfo是NSDictionary

 NSLog(@" error => %@ ", [errorOrNil userInfo] )

为我打印这样的东西

error => {
    NSLocalizedDescription = "User already exists";
    NSLocalizedFailureReason = "";
    NSLocalizedRecoverySuggestion = "Retry request based on information in `NSLocalizedFailureReasonErrorKey`";
    kinveyErrorCode = UserAlreadyExists;
    kinveyInternalErrorString = "";
    kinveyRequestId = e5be0aed155e4925b3365d57de3dc5b2;
} 

您也可以尝试:

 NSLog(@" error => %@ ", [errorOrNil localizedDescription] )

打印出来:

You got an error: User already exists 

答案 1 :(得分:1)

不是一个非常酷的解决方案 - 您可以为NSError类编写自己的类别并根据需要表示文本。