Search code examples
cocoacocoa-touchnscodingnscopying

Any reason to not use existing NSCoding methods to implement NSCopying


Is there a reason that given a class that implements NSCoding that the implementation of copyWithZone: shouldn't be implemented using this pattern:

-(instancetype)copyWithZone:(NSZone *)zone{
    return [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:self]];
}

Solution

  • Just efficiency — the encoding/decoding cost and the total memory footprint.

    Suppose you had an object with four immutable instance variables. If you implement a custom copy then you'll allocate one extra instance of that object, then give it ownership of all four instance variables.

    If you encode and decode it then there'll be the processing cost of the two-way serialisation and you'll end up with new copies of each of the instance variables.