Objective-c示例代码,故意向已释放的对象发送消息

Ale*_*ist 4 xcode objective-c nszombie nszombieenabled nszombies

我是Objective-cxcode的新手,我正在编写的应用程序正在收到臭名昭着的EXC_BAD_ACCESS错误.

几乎每个人都建议使用NSZombies开始解决问题.我想我有NSZombies正在工作,但xcode没有给我一个警告,当我的应用程序崩溃时,僵尸被消息.

在继续我的调试之前,我想运行一些代码,这些代码肯定会导致消息被发送到僵尸(解除分配的对象).

什么是简单的代码片段,其中消息被发送到解除分配的对象,导致NSZombies应该提醒我的情况?

Mar*_*sey 6

For non-ARC code:

- (IBAction) messageZombie:(id)sender {
    id a = [[NSObject alloc]init];
    [a release];
    NSLog(@"%@", [a description]);
}
Run Code Online (Sandbox Code Playgroud)

This will give you EXC_BAD_ACCESS with Zombies off, and a "message sent to deallocated instance" message, with Zombies enabled.

If your project is using ARC, then it's a bit harder to reliably-cause messages to de-allocated objects (that is the point of ARC, after all).

This works:

- (IBAction) messageZombie:(id)sender {    
    id a = [[NSObject alloc]init];
    id __unsafe_unretained b =a;
    a=nil;
    NSLog(@"%@", [b description]);
}
Run Code Online (Sandbox Code Playgroud)

It's probably not very similar to what your actual code is doing, because who the heck uses __unsafe_unretained, anyway? But if you just want to make sure that you've got NSZombies turned on properly, this should be a reasonable test case.

If you're looking for suspicious places in your code, then for sure look for __unsafe_unretained pointers, though you won't find any*, and double-check that the right casts are used for CoreFoundation objects that are casted to Cocoa objects.

*If your project needs to support OS X versions before 10.7, or iOS versions earlier than 5.0, then you can't use __weak pointers, so in that sort of project, you'd expect to find __unsafe_unretained used more often.

  • 即使僵尸关闭,这实际上也不会崩溃. (4认同)