objective-cdebuggingnszombies

Overreleasing issue and Zombies


this program crashes if i uncomment the release statements. i get that i am overreleasing and realized that quickly. but, just to test zombies, i turned them on (NSZombiesEnabled = YES and CFZombieLevel = 16) and the program runs fine and throws no exceptions.

what gives? i thought turning on zombies would have just told me what a doofus i am...not fix it.

#import "AppController.h"


@implementation AppController

-(IBAction)countCharacters:(id)sender   {
    //did a button do this?
if(![sender isKindOfClass:[NSButton class]])    {
    NSLog(@"%@ is not a button", sender);
    return;
}

//proceed
NSString *userString = [textField stringValue];
NSNumber *count = [NSNumber numberWithInt:[userString length]];
NSString *outputString = [NSString stringWithFormat:@"'%@' has %@ characters.",
                        userString, count];
//[userString release];
//[count release];
[labelField setStringValue:outputString];
//[outputString release];
}
@end

Solution

  • It's because you do not own the objects you try to release (you don't hold a reference to them). Their ownership is given to the "nearest" NSAutoreleasePool.

    You can read about object ownership here. As a quick reference, usually, you aren't the owner if you didn't call the alloc method yourself to create the object or if you didn't retain it. Retaining an object makes you an owner; calling release means you give up ownership (and will deallocate the object if it has no more owners).

    You must not release objects for which you don't have ownership. Your current code without release is exactly what you need.