Re: Memory management question
Re: Memory management question
- Subject: Re: Memory management question
- From: Ondra Cada <email@hidden>
- Date: Wed, 24 Mar 2004 22:24:36 +0100
Alastair,
On Wednesday, Mar 24, 2004, at 20:14 Europe/Prague, Alastair Houghton
wrote:
something simple like:
- (void)setStringValue:(NSString *)string
{
[string retain];
[myString release];
myString = string;
}
will work just fine...
... in most cases, but can fail too, presumed a plain getter of kind
-(NSString*)stringValue { return myString; }
is used. The problem may be risen by the fact someone can use the
getter, then use some code which happens to call the setter, and then
use the value from the getter:
NSString *s=[foo stringValue];
// some code here which, whatever indirectly, calls the setter
[s length]; // a crasher
For this reason, it's generally better if one of the accessors uses
autorelease--it may be either one. It is more safe (but of course, also
*much* less efficient) if the getter is autoreleasing (using the
pattern [[ivar retain] autorelease]); in most cases probably it is
sufficient that the setter is autoreleasing ([ivar autorelease];
ivar=[newValue retain];).
Note also that either the setter should be used to nil the ivar in
dealloc (which is IMHO considerably preferrable), or, unless the getter
is autoreleasing, in dealloc also autorelease should be used (insted of
release) to free the ivar's contents.
In 2002 this along with all the possibilities (including the black
magic of thread-safe accessors) was discussed to death and over again,
triple times: should be in the archives, subjects "Accessor methods and
(auto)release: conclusion" or "Accessors (can we close it this way?)".
---
Ondra Hada
OCSoftware: email@hidden
http://www.ocs.cz
private email@hidden
http://www.ocs.cz/oc
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.