0

I have an array of objects

I want to copy the array and all contents of it

"Object" implements NSCopying

I thought that doing

NSArray *copiedArray = [array copy];

would trigger copyWithZone in the objects contained inside of it.

Unfortunally not...

How can this be done?

Avba
  • 14,822
  • 20
  • 92
  • 192
  • You want a deep copy of the array? – Rajan Balana Nov 28 '13 at 11:57
  • 4
    @AnoopVaidya and whoever upvoted you: That's a shallow copy, the question is about creating a deep copy. – JustSid Nov 28 '13 at 11:59
  • @JustSid: I cant find he asked for deep or shallow? – Anoop Vaidya Nov 28 '13 at 12:05
  • If you want a deep copy then JustSid answer is good. For more http://stackoverflow.com/questions/647260/deep-copy-nsmutablearray-in-objective-c – Anoop Vaidya Nov 28 '13 at 12:07
  • @AnoopVaidya He says that he thought that `copy` would call `copyWithZone:` on all objects in the container, unfortunately it doesn't. It ends with `How can this be done?`. Granted, it doesn't mention deep copies explicitly, but that's what he is asking... – JustSid Nov 28 '13 at 12:08

1 Answers1

6

That depends on how deep you want the copy of the array to be. If one level is enough, - initWithArray:copyItems: is going to do the trick. If you want an actual deep copy, you have to write it yourself I'm afraid.

JustSid
  • 25,168
  • 7
  • 79
  • 97