2

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]];
}
jscs
  • 63,694
  • 13
  • 151
  • 195
Jon
  • 462
  • 4
  • 13
  • `encodeWithCoder:` might skip things that are heavy or that can easily/must be recreated. – jscs Oct 15 '14 at 02:00

1 Answers1

1

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.

Tommy
  • 99,986
  • 12
  • 185
  • 204
  • thanks. in my case i'm not worried about efficiency for these particular classes, they are very light weight. If I have a large graph with things like large immutable arrays I'll do it by hand. – Jon Oct 15 '14 at 02:32