Re: Should I retain a variable returned from this accessor?
Re: Should I retain a variable returned from this accessor?
- Subject: Re: Should I retain a variable returned from this accessor?
- From: Sean DeNigris <email@hidden>
- Date: Mon, 11 Aug 2008 20:28:38 -0400
On Mon, Aug 11, 2008 at 3:12 PM, Sean DeNigris
<email@hidden> wrote:
Hi, how do I handle memory management for todoUid below? Do I have
to
retain or autorelease it?
[...snip...]
// Get uid to return
NSString* todoUid = [newTodo uid];
[...snip...]
[newTodo release];
newTodo = nil;
return todoUid;
}
http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Tasks/MemoryManagementRules.html
"Memory Management Programming Guide for Cocoa" (mentioned above) said:
> "Another problem situation is when an object is deallocated after a
call to one of its getter methods:
> sprocket = [thingamajig mainSprocket];
> [thingamajig release];
> // sprocket could now be invalid.
> To protect against situations like this, you could retain sprocket
upon receiving it and release it when you have finished with it.
Because it may not always be obvious when a caller should retain an
object in this manner, the objects themselves should strive to
return results that are valid in the current calling scope. In many
cases, understanding how accessor methods are implemented, and
implementing accessor methods appropriately, will resolve any confusion
—see “Accessor Methods.”
This seems to suggest that todoUid should be retained and autoreleased
to safely be valid in the calling method.
You've gotten todoUid from a method that is not +alloc and does not
begin with +new or contain -copy, so you do not own it. Therefore you
must -retain it if you want to hold on to it beyond "now". Since you
don't, just let it go, it's not your responsibility.
That's it. Done. If you're really paranoid, you could instead hand
off a copy of todoUid that you know is not mutable by instead
returning [[todoUid copy] autorelease], but that seems unnecessary.
After all, your caller (and even you) can't be sure that todoUid is
mutable at all, since it's only known to be an NSString. In this
case, however, since you're using -copy, you are responsible for that
copy and so must autorelease it.
--Kyle Sluder
_______________________________________________
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