开发者

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

    NSLo开发者_JAVA技巧g(@"%@",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.


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


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."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜