views:

64

answers:

3

If I have an object created as autoreleased, is there a way that I can mark it is essentially "not autoreleased"?

I feel that I have heard calling [object retain] will do what I am looking for but I am not sure.

+2  A: 

Yes, calling [object retain] is exactly what you want.

Joshua Weinberg
+7  A: 

Depending on what you really want [object retain] will do it...or nothing will.

If what you want is "my object should live past the drain of the autorelease pool", then [object retain] will do that for you. It will make the object live until you have a matching number of [object releases]s (or [object autorelease]s + pool drains).

If you want the object to not make the autorelease pool bigger, not to make the pool drain fractionally slower, or to make sure to object dies BEFORE the next pool drain, then [object retain] will not do it. In fact the only real way to do any of those things is to make sure the object never goes into the autorelease pool (or to a lesser extent, make a private autorelease pool and manage its lifecycle).

Stripes
+2  A: 

When an object is sent autorelease, it adds itself to the autorelease pool. At each iteration of the run loop, the autorelease pool is drained. It drains itself by sending it a release message to every object in the pool. If an object is added to the pool twice, it is sent two release messages, and so on. It is a very simple mechanic that greatly simplifies memory management.

If you have an object that has already been sent an autorelease message, then by sending that same object retain, you are cancelling out the effect of what will happen when the autorelease pool is drained.

dreamlax