NSLog,NSError,访问不良

joh*_*cat 6 cocoa objective-c nslog nserror

我正在做一个相当普通的addPersistentStore NSPersistentStoreCoordinator,它生成了一个错误代码.

所以我去了NSLog它,当我这样做时出现访问错误:

    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
Run Code Online (Sandbox Code Playgroud)

这似乎是常见的习语.

当我重新格式化错误语句时,如下所示:

     NSLog(@"Unresolved error   %@",   [error userInfo]);
Run Code Online (Sandbox Code Playgroud)

......问题消失了.

甚至NSZombie也没有正确捕获错误的访问错误!

有任何想法吗?

Pet*_*sey 18

你怎么抓错了?

正如bbum描述的那样,正确的方法是:

NSError *error;
BOOL success = [blah blah:blah error:&error];
if (!success) {
    NSLog(@"Error: %@ %@", error, [error userInfo]); //Or other error handling (e.g., [NSApp presentError:error]).
} else {
    //Succeeded—ignore the error variable entirely
}
Run Code Online (Sandbox Code Playgroud)

(这是一个blah:error:返回a 的方法BOOL;问题bbum中的示例是针对返回对象的方法.错误处理模式对于两种情况都是相同的.)

不久之后,根据他的推特更新,即使你要求的成功,一些API也会输出一个错误对象,这意味着测试错误变量而不是BOOL返回可能会欺骗你.我想这就是发生在你身上的事.

解决方案是在API报告失败时查看错误对象.