What happens if your mark an autorelease object as autorelease
Asked Answered
S

2

7

My question may sound stupid an all, but I like to know what happens if I mark an autoreleased object as autorelease. Will it be released twice? Or nothing happens? For example:

 Obj * obj = [[Obj create] autorelease];

Let's say [Obj create] returns an autoreleased object.
If I add another autorelease, what happens then?

Stempien answered 18/9, 2012 at 23:40 Comment(2)
Autorelease will cause the object to receive a release message at some point, so by calling it twice, you'll end up with two release calls, over-releasing the object.Calia
+1 Nothing stupid about this question :)Farnsworth
H
5

Yes, sending autorelease twice will release the object twice. If your create method returns an autoreleased object and you send another autorelease message to it, your app will crash, because you'll be releasing a deallocated object.

Having said that, why don't you use the new Automatic Reference Counting (ARC)? You don't have to worry about (auto)releasing objects anymore.

Hoes answered 18/9, 2012 at 23:44 Comment(2)
"your app will crash" well, what exactly happens is undefinedUnni
True. If you're lucky it will crash though.Hoes
I
-2

You use the Class Method(+), you should not to care the memory. People use Class Method one reason is that it can return an autorelease object. If you release or autorelease the object which the Class Method returns, it will crash.

Indicate answered 19/9, 2012 at 3:1 Comment(3)
It has nothing to do with class or instance methods. It's just whether the method name starts with new, alloc, copy, mutableCopy, or retainUnni
@Unni what the different betweent the class and instance methods? and if i write like this use instance :Obj * obj = [[[Obj alloc] init] autorelease]; it will do fineIndicate
@Indicate Your example uses alloc a class method which is in the list @Unni gives above. As it is in the list the caller owns the returned object so it would be correct to release or autorelease the object in this case. Nothing to do with whether it is a class or instance method. [NSURL URLWithString:@"http://www.stackoverflow.com"] is a class method which returns an object that you don't own (it has already been autoreleased). If you release or autorelease an NSURL object created using URLwithString: you will over release and most likely crash.Spiritism

© 2022 - 2024 — McMap. All rights reserved.