为什么断言只是终止为 iPhone 编译的程序? [英] Why does assert simply terminate a program compiled for iPhone?

查看:27
本文介绍了为什么断言只是终止为 iPhone 编译的程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调试一个大量使用 assert() 的 iPhone 应用程序(Xcode、Objective-C++ 和设备模拟器).在某些情况下,断言失败只会终止应用程序,而不是像我预期的那样闯入调试器.

I'm debugging a heavily assert()'ed iPhone app (Xcode, Objective-C++, and device simulator). In some cases, the assert failure would just terminate the app, instead of breaking into the debugger as I'd expect.

我通过实现自己的 kinda-assert 来解决以下问题:

I made a workaround by implementing my own kinda-assert to the effect of:

#define AssertLite(b) if(!(b)) {asm {int 3}}

(省略了绒毛),但我想知道是否有人遇到过这种情况.我无法确定何时中断以及何时终止的模式.代码没有线程化;它所做的一切都是在事件处理程序中完成的.

(fluff omitted), but I wonder if anyone ever encountered this. I could not determine a pattern as to when does it break and when does it terminate. The code is not threaded; all it does is done in event handlers.

为什么会发生这种情况,我如何让 vanilla assert() 表现得像条件断点一样?

Why does this happen and how do I make vanilla assert() behave like a conditional breakpoint it should be?

推荐答案

首先,由于您正在开发 iPhone 应用程序,因此您可能应该使用 NSAssert() 而不是普通的 BSD 断言函数.

First off, since you are working on an iPhone app, you should probably use NSAssert() instead of the vanilla BSD assert function.

例如NSAssert(the_object, @"NIL 对象遇到");

如果断言失败,NSAssert 宏将抛出一个 Objective-C 异常 (NSInternalInconsistencyException).

The NSAssert macro will throw an Objective-C exception (NSInternalInconsistencyException) if the assertion fails.

由于您的目标是中断异常,下一步是使 Xcode 调试器中断 Objective-C 异常.无论如何,这可能是一件好事.

Since your goal is to break on the exception, the next step is to make the Xcode debugger break on Objective-C exceptions. This is probably a good thing to do anyway.

在 Breakpoints 窗口(Run->Show->Breakpoints 菜单项)中,点击Double-Click for Symbol"输入符号 -[NSException raise]

In the Breakpoints window (Run->Show->Breakpoints menu item), click where it says "Double-Click for Symbol" to enter the symbol -[NSException raise]

最后要注意的是 NSAsserts 不会在发布版本中编译出来.这意味着您必须准备好处理应用程序中的异常,或者您需要创建自己的宏,以便在发布版本中编译出来.

The last thing to be careful off is that NSAsserts do not compile out in a release build. That means that you have to either be prepared to handle the exception in your application, or you need to create your own macro that does compile out in release builds.

这是我用来在运行时代码中编译断言的宏(注意,我然后在我的代码中使用了 HMAssert 而不是 NSAssert):

Here's the macro I use to compile out assertions in runtime code (note that I then use HMAssert in my code instead of NSAssert):

#ifdef DEBUG
#   define HMAssert(A,B) NSAssert(A,B)
#else
#   define HMAssert(A,B)
#endif

这需要定义一个 DEBUG 预处理器宏.设置方法如下:

This requires a DEBUG preprocessor macro to be defined. Here's how to set that up:

  1. 在 Xcode 中右键单击您的项目.这将是左侧面板中列出您的项目文件的顶部项目
  2. 从弹出的上下文菜单中选择获取信息".
  3. 转到构建"标签.
  4. 确保配置"设置为调试".
  5. 在GCC 4.2 - 预处理"下的预处理器宏"旁边的字段中输入 DEBUG.

这篇关于为什么断言只是终止为 iPhone 编译的程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆