2

I have a CustomObject(of type NSObject) having an NSMutableArray property. This property contains NSDictionary objects. I need a deep copy of just the property to allow for editing in a different view controller; after editing, I desire to replace the original property with the edited deep copied property.

My question is:

  • Do I need to make a deep 'copyWithZone' ?
  • and if so, how do I implement it considering that it's just the single property that requires deep copying?

I've for now circumvented this by doing:

NSMutableArray *deepCopyArray = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:<CustomObject>instance.<propertyToDeepCopy>]]];

Although this works as NSMutableArray & NSDictionary implement NSCoding, it doesn't feel the right way, or is it? Kindly help :)

soumya
  • 3,801
  • 9
  • 35
  • 69
King David
  • 139
  • 1
  • 9

1 Answers1

0

It's an acceptable way with multiple merits:

  1. It works
  2. It's simple and obvious
  3. It's very little code
  4. It's self contained and thus easy to change in future

Any alternative would mean you iterating over the contents and manually copying everything yourself, there are a couple of reasons you might do that:

  1. You know what is truly immutable and you can avoid copying
  2. You need mutable containers (yhe dictionaries in the array

Though even in some of these cases you'd want to run a similar archive based process just using a property list instead (so you continue to write minimal code and leverage supplied SDKs).

Wain
  • 118,658
  • 15
  • 128
  • 151