Autoreleasing twice an object
Asked Answered
N

2

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

Nessim answered 2/7, 2012 at 10:23 Comment(0)
M
13

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.

Miceli answered 2/7, 2012 at 10:31 Comment(1)
What if it's not a string, but another class?Camporee
A
3

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);
Antimissile answered 2/7, 2012 at 10:31 Comment(1)
"calling autorelease on it again will just be ignored" untrue. The object gets added twice to the autorelease pool, and will be released twice when the pool is drained. Here's the documentation: developer.apple.com/library/mac/#documentation/Cocoa/Reference/…Wiggs

© 2022 - 2024 — McMap. All rights reserved.