Skip navigation.
 
mlRe: Re: Odd problem using NSCoding
FROM : Ricky Sharp
DATE : Wed Apr 06 15:00:49 2005

On Wednesday, April 06, 2005, at 06:49AM, <<email_removed>> 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)

Related mailsAuthorDate
mlOdd problem using NSCoding <java_nutt Apr 6, 09:37
mlRe: Odd problem using NSCoding Ricky Sharp Apr 6, 13:13
mlRe: Re: Odd problem using NSCoding <java_nutt Apr 6, 13:48
mlRe: Re: Odd problem using NSCoding Ricky Sharp Apr 6, 15:00
mlRe: Odd problem using NSCoding Kevin Callahan Apr 9, 06:42