Why is there no memory leak for: @property (copy) NSString * name when I don't release it in dealloc?

I disabled ARC.

I have a property in a class declared as follows:

@property(copy) NSString* name 

I set name with a constant line:

 [greeter setName:@"Jane"]; 

I implemented dealloc for my class as follows:

 -(void)dealloc{ [super dealloc]; } 

I was expecting a memory leak because I did not release name . I use Xcode 6.2, and Product>Analyze does not identify any leaks, and neither the tools nor the tools: Product>Profile, choose Leaks, hit the red Record button .

Here is the 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 am a Greeter"]; return [msg autorelease]; } -(void)dealloc{ [super dealloc]; } @end 

...

 @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. Greeter* greeter = [[Greeter alloc] init]; [greeter setName:@"Jane"]; //constant string in memory for life of program NSLog(@"%@", greeter); [greeter release]; return YES; } 

After thinking about this for a while, the only explanation I can come up with is that the name setter does not actually copy the constant string. It seems that Obj-C is checking the type for the string being assigned to the property, and since it is a constant string, Obj-C simply sets (?) the-pointer-to-the-constant-string to name-pointer . Is something like this happening?

+8
memory-leaks objective-c ios8
source share
1 answer

There are two optimizations here that together lead to this result.

First: NSString literals are stored in a special segment of the binary code, and are not distributed at runtime. They ignore conservation and liberation and are never allocated or liberated.

Second: copying an immutable NSString (including a string literal) instead just saves it, because the copy will always always be identical to the original. (This is achieved by overriding the -retain and -release methods in a private subclass of NSString)

So, in your script, the copy turns into a save, the save is ignored, and the release will not happen, even if you correctly issued the line in dealloc.

+10
source share

All Articles