Re: Overriding -copyWithZone: the right way
Re: Overriding -copyWithZone: the right way
- Subject: Re: Overriding -copyWithZone: the right way
- From: Jean-Olivier Lanctôt <email@hidden>
- Date: Fri, 5 Nov 2004 18:27:57 -0500
Well I just learned a new thing...
anyway, I have this very WEIRD crash in my app (which is, BTW, the
ONLY bug left until I can release 1.0) that I just can't squash.
*Maybe* it has to do with my wrong manner of overriding copyWithZone??
What do you guys think.. I have something like 5 custom classes
implementing it and I don't do it the right way... so could that be
the reason for weird crashes? I'm not on my work comp. right now so I
can't check.
On Fri, 5 Nov 2004 23:24:40 +0100, M. Uli Kusterer
<email@hidden> wrote:
> At 15:50 Uhr -0600 05.11.2004, Evan Schoenberg wrote:
> >If the superclass supports copyWithZone and you therefore use [super
> >copyWithZone:zone], keep in mind that your instance variables will
> >be 'lightly' (not sure the proper word) copied - they point to the
> >same memory addresses but are NOT retained.
>
> "Shallow copy" is what you're fishing for.
>
>
>
> >You therefore want to manually set all of your subclass's instasnce
> >variables, like so:
> >
> >//Copy
> >- (id)copyWithZone:(NSZone *)zone
> >{
> > MyClass *newCell = [super copyWithZone:zone];
> >
> > /* Font is a retained NSFont* */
> > [newCell setFont:font];
> >
> > /* subString is a retained NSString* */
> > [newCell setSubString:subString];
> > return(newCell);
> >}
>
> No! If your setFont: looks like the typical one:
>
> -(void) setFont: (NSFont*)f
> {
> if( font != f )
> {
> [font release];
> font = [f retain];
> }
> }
>
> This will simply do nothing, and thus not retain the instance
> variable. Or if you're using the other variant:
>
> -(void) setFont: (NSFont*)f
> {
> [font autorelease];
> font = [f retain];
> }
>
> This will release an object that was never retained by you, thus
> effectively also failing to do the additional "retain" needed to give
> your copy ownership of the NSFont. Apple recommends to do:
>
> -(id) copyWithZone: (NSZone*)zone
> {
> MyClass *newCell = [super copyWithZone: zone];
>
> newCell->font = nil;
> [newCell setFont: font];
>
> newCell->subString = nil;
> [newCell setSubString: subString];
>
> return newCell;
> }
>
> --
>
>
> 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
>
--
--Olivier
_______________________________________________
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