objective c - Why no memory leak for: @property(copy) NSString* name, when I don't release it in dealloc? -
i turned arc off.
i have property in class declared this:
@property(copy) nsstring* name
i set name
constant string:
[greeter setname:@"jane"];
i implemented dealloc
class this:
-(void)dealloc{ [super dealloc]; }
i expected there memory leak because didn't release name
. i'm using xcode 6.2 , product>analyze
not identify leaks, , neither instruments: product>profile, choose leaks, hit red record button
.
here relevant code:
// // greeter.h // flashlight2 // #import <foundation/foundation.h> @interface greeter : nsobject @property(copy) nsstring* name; -(nsstring*)description; -(void)dealloc; @end
....
// // greeter.m // flashlight2 // #import "greeter.h" @implementation greeter -(nsstring*)description { nsstring* msg = [[nsstring alloc] initwithstring:@"i greeter"]; return [msg autorelease]; } -(void)dealloc{ [super dealloc]; } @end
...
@implementation appdelegate - (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { // override point customization after application launch. greeter* greeter = [[greeter alloc] init]; [greeter setname:@"jane"]; //constant string in memory life of program nslog(@"%@", greeter); [greeter release]; return yes; }
after thinking awhile, explanation can come name setter
doesn't actually copy constant string. seems obj-c type check on the string being assigned
property, , because it's constant string, obj-c assigns(?) the-pointer-to-the-constant-string
name-pointer
. going on?
there's 2 optimizations @ work here combine cause result.
first: nsstring literals stored in special segment of binary, rather allocated @ runtime. ignore retain , release, , never allocated or deallocated.
second: copying immutable nsstring (including string literal) instead retains it, because copy guaranteed identical original. (this accomplished overriding -retain , -release methods in private nsstring subclass)
so in scenario, copy turns retain, retain ignored, , deallocation wouldn't happen if did release string in dealloc.