Re: Retaining a NSURL and retaining its -path
Re: Retaining a NSURL and retaining its -path
- Subject: Re: Retaining a NSURL and retaining its -path
- From: Jens Alfke <email@hidden>
- Date: Sat, 12 Sep 2009 11:41:42 -0700
On Sep 12, 2009, at 9:43 AM, John Love wrote:
Basic question: if a parent object is retained, why isn't each
sibling component object of that parent retained??
It's not a component object in the implementation. Whenever you call -
path, the NSURL implementation copies out and decodes the path portion
of the URL string, puts it in a new NSString object, autoreleases it,
and returns it. If you don't retain that NSString, it will go away
when the current autorelease pool exits. That's why your app crashed.
The moral is that you have no way of knowing the natural lifespan of
an object returned by an accessor method. It might be, as you assumed,
kept in an instance variable of the parent object and lives as long as
the parent. But it equally well might be created on the fly. Or there
might be a more complex relationship, where the property object is
cached for a while but sometimes released. You have no way of telling.
The point is that if you follow the rules it won't matter to you. (And
it shouldn't matter, because a property that's implemented one way in
one release might change its implementation in the next, and you
wouldn't want that to break your app.)
If you get an object returned from a method (other than +alloc, -copy
and a few other exceptions) and you want to hang onto it, you must
retain or copy it. Period. (Or you could make your app garbage
collected, assuming it's not on iPhone, and not worry about these
rules.)
—Jens_______________________________________________
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