NSLog、NSError、访问错误

发布于 2024-08-14 21:19:17 字数 431 浏览 12 评论 0原文

我正在对 NSPersistentStoreCoordinator 执行一个相当普通的 addPersistentStore,它生成了一个 & 错误代码。

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

    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

这似乎是常见的习惯用法。

当我按如下方式重新格式化错误语句时:

     NSLog(@"Unresolved error   %@",   [error userInfo]);

...问题消失了。

即使 NSZombie 也没有正确捕获错误的访问错误!

有什么想法吗?

I was doing a rather ordinary addPersistentStore to an NSPersistentStoreCoordinator, and it generated an &error code.

So I went to NSLog it, and got an access error when I did this:

    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

which seems to be the common idiom.

When I reformatted the error statement as follows:

     NSLog(@"Unresolved error   %@",   [error userInfo]);

...the problem went away.

Even NSZombie didn't trap the bad access error correctly!

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

东北女汉子 2024-08-21 21:19:17

你如何捕获错误?

正如 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
}

:(这是一个返回 BOOL 的方法;bbum 回答的问题中的示例是返回一个对象的方法。两种情况都相同。)

根据他不久后的 Twitter 更新,一些 API 将在后台输出错误对象即使您请求的内容成功了,这意味着测试错误变量而不是 BOOL 返回值可能会欺骗您。我想这就是发生在你身上的事情。

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

How are you catching the error?

The correct way, as described by bbum, is:

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
}

(That's for a method blah:error:that returns a BOOL; the example in the question bbum answered was for a method that returned an object. The error-handling pattern is the same for both cases.)

According to his Twitter updates shortly afterward, some APIs will output an error object under the hood even if what you asked for succeeded, which means that testing the error variable instead of the BOOL return can fool you. I think this is what happened to you.

The solution is to only look at the error object if the API reports failure.

动次打次papapa 2024-08-21 21:19:17

不要忘记用 nil 值初始化 NSError

NSError* err = nil;
[anObject doSomethingGetError:&err];
if (err) {
    NSLog(...);
}

如果这没有帮助,那是 API bug

Do not forget to init NSError with nil value

NSError* err = nil;
[anObject doSomethingGetError:&err];
if (err) {
    NSLog(...);
}

If that does not help, it is API bug

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文