Re: Re: Odd problem using NSCoding
Re: Re: Odd problem using NSCoding
- Subject: Re: Re: Odd problem using NSCoding
- From: Ricky Sharp <email@hidden>
- Date: Wed, 06 Apr 2005 08:00:49 -0500
On Wednesday, April 06, 2005, at 06:49AM, <email@hidden> wrote:
>Do I need to override copyWithZone? If so, how do you suggest I do this? I'll be hitting Cocoabuilder.com and searching the archives as well, but I thought I'd ask since I have you here. :) Thanks again, Rick. Oh, and I switched everything over to encode/decodWithObject/int: forKey: as well. Thanks for the tip.
I use the following patterns when implementing copyWithZone:
- (id)copyWithZone:(NSZone*)aZone
{
MyObject* theCopy = [[MyObject allocWithZone:aZone] init]; // Or whatever your designated initializer is
[theCopy setAttributeOne:[self attributeOne]];
[theCopy setAttributeTwo:[self attributeTwo]];
...
return theCopy;
}
If you have tons of ivars and you're KVC savvy, consider using an NSDictionary as an intermediate step:
- (id)copyWithZone:(NSZone*)aZone
{
MyObject* theCopy = nil;
NSDictionary* theDictionary = [self dictionaryWithValuesForKeys:[self keyPaths]];
if (theDictionary != nil)
{
theCopy = [[MyObject allocWithZone:aZone] init]; // Or designated initializer
[theCopy setValuesForKeysWithDictionary:theDictionary];
}
return theCopy;
}
where keyPaths would be something like this:
- (NSArray*)keyPaths
{
return [NSArray arrayWithObjects:@"attributeOne", @"attributeTwo", ..., nil];
}
In the patterns shown above, accessors are used to do all the work. But, if doing so, ensure your accessors will be doing what you want. Sometimes you'll want to make a copy of the ivar rather than simply obtaining its reference.
For example, if a particular getter is coded as...
- (NSString*)studentName
{
return [[studentName retain] autorelease];
}
... and in copyWithZone: you'd really want to obtain a copy, you'd have to do the more "manual labor" approach and do this inside copyWithZone:
[theCopy setStudentName:[[self studentName] copy]]; // or mutableCopy
However, I don't know if it's a "bad thing" to have such situations. i.e. not have your accessors be implemented such that they could be called as-is from within copyWithZone (or indirectly with the NSDictionary approach).
I'm sure google/archives will turn up other patterns.
--
Rick Sharp
Instant Interactive(tm)
_______________________________________________
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