views:

69

answers:

2

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
+1  A: 

Well, zombies will tell you when a free'd object receives a release correct? So, if your not sending the release (you commented it out) you won't see the zombies complaining?

Your NSString/NSNumber methods are all convenience methods, and you don't have to release them. So -yeah, You solved the problem yourself.

Mr-sk
+2  A: 

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.

zneak
Exactly correct. In other words, if you were to uncomment the commented lines, then run Zombies, the zombie logging mechanism would trigger.
bbum
thank you, that makes sense. i knew i shouldn't release them, but it didn't click as to why not.
griotspeak
@bbum, but they didn't...that was the point of the question
griotspeak
If it isn't triggering and you know the autorelease poole is being drained, please file a bug.
bbum