objective-cxcodenszombienszombieenablednszombies

Objective-c example code that intentionally messages a deallocated object


I'm new to objective-c and xcode and an app I'm currently writing is receiving the infamous EXC_BAD_ACCESS error.

Almost everybody recommends starting to solve the problem using NSZombies. I think I have NSZombies working but xcode isn't giving me an alert about a zombie being messaged when my app crashes.

Before I move on with my debugging, I'd like to run some code that should for sure result in a message being sent to a zombie (de-allocated object).

What is a simple code snippet where a message is sent to a deallocated object, causing a scenario where NSZombies should alert me?


Solution

  • For non-ARC code:

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

    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]);
    }
    

    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.