Re: Releasing what's in an array?
Re: Releasing what's in an array?
- Subject: Re: Releasing what's in an array?
- From: Mark Dawson <email@hidden>
- Date: Fri, 25 Feb 2005 11:42:43 -0800
Charlton,
That was the key to my puzzle--adding elements to an array causes a
retain to be done on them. Your idea of releasing an object after
adding (if you want the array release to dealloc the object) is a good
one.
Thanks for everyone's input!
Mark
Does this mean that you have to do extra work if you release an array
with objects that should NOT be released by you (i.e., objects you
did NOT allocate)?
No. Collection classes retain any object that is added to them, and
release objects that are removed from them. (This means that an
object can "go away" from underneath your code if you remove it from
an array.) At deallocation, they release any objects that are still
in them.
If you have an object you did not allocate and add it to an array, its
retain count will be increased by one while it is in that array, and
when you remove it from the array its retain count will be decreased
by one. If it was retained elsewhere before you got your hands on it,
it will still be retained elsewhere after it is removed from the
array; if it was not retained elsewhere (perhaps because it had been
autoreleased when you got your hands on it, and the autorelease pool
was released after you added it to the array), it will be deallocated
when it is removed from the array.
If you have an object you did allocate, it's often wise to release it
after adding it to the array and then later retain it if you want to
remove it from the array - it's simpler to match an alloc/release
around adding it to the array and a retain/release around removing it
from the array than it is to match an alloc around adding it to the
array with a release around removing it from the array; in particular,
you know when you allocate or otherwise obtain the object whether you
need to release it, while you might not know that when you remove it
from the array.
Charlton
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden