当将应用程序部署到设备时,程序将在几个周期后退出,并出现以下错误:

Program received signal: "EXC_BAD_ACCESS".

程序在iPhone模拟器上运行没有任何问题,只要我一次执行一个指令,它也会调试和运行。一旦我让它再次运行,我将击中EXC_BAD_ACCESS信号。

在这种特殊情况下,它恰好是加速度计代码中的一个错误。它不会在模拟器中执行,这就是它不会抛出任何错误的原因。但是,它将在部署到设备后执行。

这个问题的大多数答案都处理一般的EXC_BAD_ACCESS错误,因此我将保留这个选项,作为可怕的坏访问错误的统称。

EXC_BAD_ACCESS通常是非法内存访问的结果。你可以在下面的答案中找到更多信息。

您以前遇到过EXC_BAD_ACCESS信号吗?您是如何处理它的?


当前回答

如果您正在使用自定义字体,并且以编程方式实例化它们,则如果您之前没有在运行时注册字体,则会发生此错误。

为了确保是这样,Xcode控制台将打印如下内容:

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x1d8)
    frame #0: 0x0000000180f969cc CoreText`CTFontGetClientObject + 12
...

or

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    frame #0: 0x000000012341c10e CoreFoundation`CFRelease.cold.1 + 14
    frame #1: 0x00000001232ed7bd CoreFoundation`CFRelease + 77
    frame #2: 0x0000000128136990 libGSFont.dylib`GSFontGetExtraData + 112
    frame #3: 0x0000000135bc8958 UIFoundation`-[UIFont lineHeight] + 9
    frame #4: 0x00000001340149f3 UIKitCore`-[UILabel intrinsicContentSize] + 331
...

要注册自定义字体并解决该问题,可以签出此解决方案:https://stackoverflow.com/a/69756114/3701102

其他回答

甚至还有另一种可能:在队列中使用块,很容易发生你试图访问另一个队列中的对象,这个对象此时已经被取消分配了。通常当你试图向GUI发送一些东西时。 如果异常断点设置在一个陌生的位置,那么这可能是原因所在。

在EXC_BAD_ACCESS异常发生之前捕捉异常的另一种方法是XCode 4+中的静态分析器。

使用Product > Analyze (shift+cmd+B)运行静态分析器。 单击分析器生成的任何消息将在您的源上覆盖一个图表,该图表显示了保留/释放违规对象的顺序。

在创建字符串时不要忘记@符号,将c -string作为nsstring将导致EXC_BAD_ACCESS。

用这个:

@"Some String"

而不是这样:

"Some String"

PS——通常是在填充包含大量记录的数组内容时。

根据我的经验,这通常是由非法内存访问引起的。检查所有指针,特别是对象指针,以确保它们已初始化。确保你的主窗口。Xib文件(如果您正在使用的话)已正确设置,并具有所有必要的连接。

If none of that on-paper checking turns anything up, and it doesn't happen when single-stepping, try to locate the error with NSLog() statements: sprinkle your code with them, moving them around until you isolate the line that's causing the error. Then set a breakpoint on that line and run your program. When you hit the breakpoint, examine all the variables, and the objects in them, to see if anything doesn't look like you expect.I'd especially keep an eye out for variables whose object class is something you didn't expect. If a variable is supposed to contain a UIWindow but it has an NSNotification in it instead, the same underlying code error could be manifesting itself in a different way when the debugger isn't in operation.

我如何处理EXC_BAD_ACCESS

有时候我觉得当一个EXC_BAD_ACCESS错误被抛出时,xcode会在主代码中显示错误。m类没有提供崩溃发生的额外信息(有时)。

在这种情况下,我们可以在Xcode中设置一个异常断点,这样当异常被捕获时,就会设置一个断点,并直接通知用户崩溃已经发生在那一行