Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoreleasing twice an object

NSString *str = [[[[NSString alloc]init]autorelease]autorelease];
str = @"hii";
NSLog(@"%@",str);      

Can any one help me to tell about this code. Autoreleasing the object twice what will happened. When i run the code i didn't get any zombie. why it so.

like image 964
Vipin Vijay Avatar asked Jul 02 '12 10:07

Vipin Vijay


2 Answers

The object gets released twice when the autorelease pool is destroyed, which is probably going to be at the end of the run loop iteration. Why it doesn't crash is, that NSString returns singletons for some instances, for example the empty string you create or string literals (you should NOT depend on it, thats just what currently happens!), these objects won't be deallocated and this is why you don't get a zombie.

like image 156
JustSid Avatar answered Nov 10 '22 07:11

JustSid


First of there is no reason to call autorelease twice.

Once an object is marked as autorelease, calling autorelease on it again will just be ignored. See https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsautoreleasepool_Class/Reference/Reference.html

But in the exmaple you posted you are creating an empty string:

NSString *str = [[[[NSString alloc]init]autorelease]autorelease];

Then you assign an other string to it:

str = @"hii";

This means that the first string you allocated is just going to be leak, you did autorelease it so it will be cleaned up at the end. But there is not reason to allocated the string in fist place.

You could just do:

NSString *str =@"hii";
NSLog(@"%@",str);
like image 33
rckoenes Avatar answered Nov 10 '22 08:11

rckoenes