Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my object still work after countless releases?

I can never seem to deallocate my NSMutableString as shown below. The initial retain count should be 1, but after releasing several times, the string is still usable like nothing happened!

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    NSMutableString* s = [[NSString alloc]initWithString:@"AAA"];
    [s release];
    [s release];
    [s release];
    [s release];
    [s release];

    NSLog(@"%@",s);

    [pool drain];
    return 0;
}

Of course, if I use Analyze it still tells me that I release a released object on the second release.

like image 981
Sargon Avatar asked Dec 03 '22 07:12

Sargon


2 Answers

Scott's answer is the correct general one, but in this particular case, the reason is that NSString literals (i.e. @"") are uniqued compile-time constants and do not actually do anything at all when retained and released. Your assignment of it to an NSMutableString* does not actually make it an NSMutableString, so what you've written is equivalent to

[@"AAA" release];
[@"AAA" release];    
[@"AAA" release];
[@"AAA" release];
[@"AAA" release];
[@"AAA" release];
like image 144
Catfish_Man Avatar answered Dec 18 '22 02:12

Catfish_Man


Releasing an object tells the runtime that it can destroy the object, at least as far as you're concerned, but it doesn't require that the object be destroyed immediately: After your first [s release], Cocoa is free to do whatever it pleases with the memory formerly used by s. It might give that memory to the next object that does an alloc, in which case your later attempts to access s will result in a fiery runtime crash… or it might not need that memory right away, in which case you might get away with accessing a released object.

The rule of thumb is less "I've released this object, which means it no longer exists" and more "I've released this object, which means it's no longer guaranteed to exist."

like image 21
Scott Forbes Avatar answered Dec 18 '22 01:12

Scott Forbes