Re: resetting ivars safely
Re: resetting ivars safely
- Subject: Re: resetting ivars safely
- From: Uli Kusterer <email@hidden>
- Date: Fri, 14 Sep 2007 08:50:16 +0200
On 13.09.2007, at 17:24, Daniel Child wrote:
It seems to me there are two approaches.
A. Use a convenience constructor....
[NSMutableArray array] OR
[NSMutableArray arrayWithCapacity:]
But do I have to worry that it will get autoreleased prematurely?
Read up on the memory contract. Unless you create an autorelease
pool in your method, there's only one outside your function, so
that's the earliest time at which any of these objects can be
released [1].
B. Use alloc init autorelease [[NSMutableArray alloc] init]
autorelease].
Same question: could it get released too soon?
You're autoreleasing it. Are you creating and releasing a pool? No?
Then it is guaranteed to stay around for the duration of your method
call, because the first pool can be outside your method, at the
earliest.
C. Use allloc + init and release elsewhere. But I'm not sure there
is an elsewhere that works. Is that correct?
Well, since your setter retains the object, you could do (pseudocode):
myFoo = [[NSFoo alloc] init]
[self setFrobnitz: myFoo]
[myFoo release]
and while your function shouldn't use the object afterwards
("release" means "I'm done using this object" -- unless you know you
hold another reference to this object, e.g. since you retained your
object twice, you shouldn't use the object after a release).
Actually, I'm using release ... copy, but I guess it amounts to the
same thing.
Yes. copy creates an object that you own, retain acquires ownership
of an object, so for this discussion they're exchangeable. But you're
right, to be more exact, I should have simply said that the setter
acquires ownership.
1) After all, these are convenience constructors, not methods that
give you an object owned by the receiver, so you don't have to worry
about destroying the receiver. If they weren't convenience
constructors, like -objectAtIndex:, the object could go away earlier,
when you release the array that contains the object. But this is not
the case here.
Cheers,
-- M. Uli Kusterer
http://www.zathras.de
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden