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: Brian Stern <email@hidden>
- Date: Tue, 12 Aug 2008 12:51:33 -0400
On Aug 11, 2008, at 10:51 PM, Peter N Lewis wrote:
I'm no Cocoa expert, but I think you're wrong on this, you've missed
out a crucial line:
At 3:12 PM -0400 11/8/08, Sean DeNigris wrote:
// Get uid to return
NSString* todoUid = [newTodo uid];
// Clean up
[newTodo release];
newTodo = nil;
return todoUid;
[newTodo release] is not [newTodo autorelease]. So it may
immediately call dealloc and dealloc the uid returned by by [newTodo
uid]. To avoid this, you could do:
Not really. This line:
// Add the todo to my iCal calendar
[[myCalendar todos] addObject:newTodo];
would appear to add newTodo to an NSMutableArray, which implicitly
retains it. So this method retains newTodo twice but releases it
once. As a result the todoUid string won't be released, as you fear,
upon sending release to newTodo.
NSString* todoUid = [[[newTodo uid] retain] autorelease];
It is quite possible that [newTodo uid] does exactly the above, but
it might just return the internal ivar. If this is not true, I
would very much like to be corrected!
Advice on this list that I think is good advice is to always use
autorelease unless there is really good reason not to (eg, with a
large number of objects in a loop).
One can think of two kinds of objects that end up in the autorelease
pools. Temporary objects that will be autoreleased in one autorelease
cycle and other objects that will remain in the autorelease pool
indefinitely because their purpose demands persistence. In the name
of efficiency one might prefer that objects in this second group not
be put in autorelease pools since their memory management can be more
precisely controlled with alloc/init and release. Placing them in an
autorelease pool will incur some overhead in memory and cpu time each
time that the pool tries to drain. The pattern for this second kind of
object is exactly what the OP used in his code. alloc/init followed
by a retain (usually implicit in addObject: or addSubview:) followed
by release. Usually the release is the next line after the
addObject:, not at the end of the method as the OP used.
You can count this as 'a really good reason' or not but IMO the OP has
no reason to autorelease the object as you suggest.
--
Brian Stern
email@hidden
_______________________________________________
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