views:

25

answers:

1

I thought the object returned by NSMutableDictionary dictionaryWithCapacity: would be released when the autorelease pool in main.m is drained. Instead, when i assign this to an instance member in -init, i find the object only lasts as long as the -init call.

What is managing the release of the object returned by NSMutableDictionary dictionaryWithCapacity:?

To further mystify what is going on here, i find that when i assign an object of a custom class created by a convenience constructor to an instance member in init, that instance is still "alive" in (for example) touchBegan: ...

+2  A: 

Generally speaking, APIs like this one return autoreleased instances.

That would mean that when the Autorelease pool drains, the object will be destructed. If you don't manage the Autorelease pool yourself, then it should be destructed when you next return to the message queue (assuming you're on the UI thread).

Internally, the OS pushes and pops an autorelease pool around each event that calls into your code. So, if you have a -touchBegan, there will be a new pool pushed before -touchBegan gets called, and it will be popped as soon as -touchBegan returns.

If that's not what you want, you'll have to retain yourself.

Andrew Shelansky
ok, that would make sense to me, except that objects with autorelease called on them returned by my own classes convenience constructors do not seem to be released in the same way.
james
@james: when do you [autorelease] them? Because if you [autorelease] them at a time when your pool is the only one on the stack, then it goes in that pool. (All that [autorelease] does is add the item to the list of things for the current top-of-stack pool to clear out when drained)
Andrew Shelansky
@james: If you want to know why your methods behave a certain way, we'll need to see the methods and possibly the context in which they are used.
Chuck