如何让 NSAssert 使应用程序崩溃或至少弹出一个错误对话框?

发布于 2024-09-09 03:09:14 字数 244 浏览 3 评论 0原文

我在代码中使用了很多断言,因为它们在调试中很有用,但是 Cocoa 应用程序的标准行为是中断处理并将断言失败记录到控制台。UI 不会崩溃,也不会弹出错误对话框而且发生的事情往往并不明显。

使程序崩溃(至少可以得到跟踪)或弹出错误对话框的最简单方法是什么?

我是否需要提供一个断言处理程序(看起来非常复杂!)?或者我可以在运行循环中捕获异常吗?

是否有任何示例代码可用于说明如何最好地做到这一点?

感谢您的帮助。

I use asserts quite a bit in my code since they are useful in debugging, but the standard behaviour of Cocoa applications is to interrupt processing and logging the assertion failure to the console.. the UI stays up neither crashing, nor bringing up an error dialog and it's often not obvious what has happened.

What's the easiest way of either crashing the program (at least then you get a trace) or bringing up an error dialog?

Do I need to supply an assertion handler (that looks very complicated!)? or can I catch exceptions in the run loop are something?

Is there any example code available anywhere on how to best do this?

Thanks for your help.

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

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

发布评论

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

评论(1

苏璃陌 2024-09-16 03:09:14

回答你的问题的主题:你不知道。

要立即崩溃:abort();

要引发错误,只需创建 NSError 对象,并填写描述(自定义消息、错误号等),然后要求 NSApp -presentError:

我建议你走 NSError 路线。 Cocoa 为您提供了大量的错误处理甚至错误恢复功能。提供错误(以及为用户提供潜在的恢复选项)比简单地崩溃要好得多。毕竟,如果您知道哪里会发生错误(足以在那里调用 abort())并且您知道您所断言的内容(足以使用 NSAssert),那么您就足够了解如何要么自动恢复,要么为用户提供选项,以便他们决定要做什么。

查看 错误处理编程指南了解详细信息。

In answer to the subject of your question: You don't.

To crash immediately: abort();

To raise an error, simply create the NSError object, complete with description (for custom message, error number, etc.), and ask NSApp to -presentError:

I recommend you go the NSError route. Cocoa gives you a LOT of error handling and even error recovery capabilities. It's infinitely better to provide an error (and potentially recovery options for the user) than to simply crash. After all, if you know where an error is going to occur (enough to call abort() there) and you know what you're asserting (enough to user NSAssert), then you know enough about how either to recover automatically or to give options to the user so they can decide what to do.

Check out the Error Handling Programming Guide for details.

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