Re: Beginner memory management question
Re: Beginner memory management question
- Subject: Re: Beginner memory management question
- From: Scott Ribe <email@hidden>
- Date: Thu, 04 Dec 2008 09:47:32 -0700
- Thread-topic: Beginner memory management question
A few things to note:
As was already pointed out, you meant if(newName != nil) [newName release],
but note that it's not an error to send a message to nil (as long as you're
not using a return value, then there are rules as to whether it's safe or
not), so you could just do [newName release].
Also, retain returns the argument for a good reason, to allow you to write
newName = [[stockName stringValue] retain].
Finally, what if the current value of newName and [stockName stringValue]
are the same instance? Then you're releasing it before you're retaining it.
In this case, stockName has still retained it, so no harm done. But consider
a method like this:
-(void) setSomeValue: (NSString*) newVal {
[curVal release];
curVal = [newVal retain];
}
If you call that with the same value that curVal already has, and no other
code anywhere is holding a retain, then you can wind up dealloc'ing curVal,
which is newVal, before you retain it.
So, a couple of ways to deal with this:
-(void) setSomeValue: (NSString*) newVal {
[curVal autorelease];
curVal = [newVal retain];
}
-(void) setSomeValue: (NSString*) newVal {
if( newVal != curVal ) {
[curVal release];
curVal = [newVal retain];
}
}
Or use properties, or use garbage collection--assuming your project's
targeted versions/platforms will allow you to.
Above all, read this before going any further:
<http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Tasks/
MemoryManagementRules.html>
--
Scott Ribe
email@hidden
http://www.killerbytes.com/
(303) 722-0567 voice
_______________________________________________
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