Re: Overriding -copyWithZone: the right way
Re: Overriding -copyWithZone: the right way
- Subject: Re: Overriding -copyWithZone: the right way
- From: "M. Uli Kusterer" <email@hidden>
- Date: Tue, 9 Nov 2004 14:38:53 +0100
At 20:04 Uhr -0500 08.11.2004, The Karl Adam wrote:
-(id) copyWithZone: (NSZone*)zone {
MyClass *newCell = [[self allocWithZone:zone] init]; // we know
how to do this thanks to NSObject
Here's a typo: This should be [self class]. allocWithZone: is a
class method, not an instance method.
-(id) copyWithZone: (NSZone*)zone {
MyClass *newCell = (MyClass *)[super copyWithZone:zone]; // you
need to cast up to your subclass
// then set your memory state using the memory selectors and point to
what you already have
newCell->font = font;
newCell->subString = subString;
return newCell;
}
This is buggy as well. You can't just assign font and subString when
they are objects, because usually your class will need to retain
them. So this should be:
newCell->font = [font retain];
newCell->subString = [subString retain];
or, if you follow the recommendation from many pros that you should
*always* use accessors to manipulate your variables, you should do
what Apple does in its sample code:
newCell->font = nil;
[newCell setFont: font];
newCell->subString = nil;
[newCell setSubString: subString];
Again, remember that the nil assignment is necessary if the super
calls NSCopyObject(), which performs a shallow copy, meaning there
are un-retained pointers in those variables. However, you can only do
this if you know that super calls NSCopyObject, because if it just
calls allocWithZone and init, then these pointers have already been
retained, and you actually need to use the accessor to ensure the old
value is released and the new one retained.
Don't ask me why it's so complicated. I guess NSCopyObject() was
created for classes that mostly contain data and few pointers to
objects.
--
Cheers,
M. Uli Kusterer
------------------------------------------------------------
"The Witnesses of TeachText are everywhere..."
http://www.zathras.de
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden