NSCopying Protocol in Objective C
This is part of iOS Basics series.
Reference code can be found here. (git log tag is v1.5)
(Changes 31010af9b57a43cf19fd01730660244a9bf08f17 & fa6dc300c9e432ca83bdc60572596894c17e7321)
In the previous post we saw we had to introduce a copyMe or deepCopyMe method so that we can make a copy of our own object. But problem with this method, is that every creator of class can name his copying method as he wishes to. In a big code, figuring this out would be difficult.
Objective C offers a simple solution, in the form of NSCopying / NSMutableCopying & NSObject.
Any method needing to implement a copy function, should call copy and/or mutableCopy of NSObject.
Internally copy & mutableCopy call copyWithZone & mutableCopyWithZone respectively.
Since we want to perform deep Copy our AddressBook and ContactCard classes, both the classes conform to NSCopying protocol.
(Note: Deep Copy or Shallow Copy is a matter of choice. It depends on what program expects at the end.)
As can be seen, there are following steps that take place underhood when a (deep) copy of Addressbook is requested.
a) Call "copy" function of AddressBook
b) Call "copy" function of ContactCard
c) Call "copy" function of NSString to create separate copies of email & name variables.
We can implement a similar implementation for NSMutableCopying protocol.
This is last post under iOSBasics tutorials.
















