Quote:
Originally Posted by jsd
I'm trying to learn but it honestly doesn't make any sense to me right now. I haven't dealt with anything this low level since 6502 assembler in the 80's. Mostly I've been doing php and perl which manage memory for you.
All I know is I have a Dictionary and I want to return a pointer to something within that dictionary. Do I retain it? Seems like yes, since I want the pointer to point to valid stuff... But if I retain it, how will it ever get freed? It seems crazy to have the function on the other end deal with releasing it. But maybe that's right? I dunno... it hasn't "clicked" yet.
|
You are absolutely correct that it is wack to release it from another method and to have some implicit contract like that.
Anytime you use "alloc", you have allocated memory, and the rules state that since you allocated, *you* are responsibile for deallocating (i.e. releasing) at some point.
Pretty shortly though, you'll realize the problem you had, where you allocate memory, but you need that value to exist for the next method, so you cannot call "release".
That's where autorelease comes into play. If you call autorelease on something you have just allocated, the value is valid for the remainder of the life of the callstack essentially, and only when it is done is the value released.
So essentially you can pass that value around from method to method in a chain of method calls and returns, and it remains valid until the chain has ended.
And since the value is released, you have fulfilled your responsibility of releasing the memory at some point.
On the other side of the equation, if you obtain a value from some object or class without "alloc" then consider it a temporary value that will only exist for the life of the callstack. If you need it to exist for longer than this, whatever needs that value should call retain on it. But by calling retain, it should also call release at some point, so there are no leaks.
It makes sense to design your software so that the entity that needs the value to stick around as more than a temporary value calls retain. You'll see that the NS framework is written like this as well. For example, an NSArray will retain its contents itself, and you do not need to call retain on each individual element you have added to the array.