Why is my facility still working after countless releases?

I will never be able to free my NSMutableString , as shown below. The initial hold value should be 1, but after releasing it several times, the string is still in use, as 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 the selected object in the second release .

+4
source share
2 answers

Releasing an object tells the runtime that it can destroy the object, at least as much as possible, but it does not require immediate destruction of the object: after the first [s release] , Cocoa is free to do whatever it wants with the memory previously used by s . It can pass this memory to the next object that alloc , in which case your subsequent attempts to access s will cause a fire failure at runtime ... or it may not need this memory right away, in which case you can leave with access to the released object.

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

+8
source

Scott's answer is the correct general one, but in this particular case, the reason is that NSString literals (ie @ "") are unique compile-time constants and do nothing at all when saving and releasing. Your assignment of NSMutableString * to it does not actually make it NSMutableString, so what you wrote is equivalent to

 [@"AAA" release]; [@"AAA" release]; [@"AAA" release]; [@"AAA" release]; [@"AAA" release]; [@"AAA" release]; 
+9
source

All Articles