Implementing the <NSCopying> Protocol

If you try to use the copy method on one of your own classes (for example, on your address book) as follows

newBook = [myBook mutableCopy];

you’ll get an error message that looks something like this:

*** -[AddressBook copyWithZone:]:  selector not recognized*** Uncaught exception:*** -[AddressBook copyWithZone:]: selector not recognized

As noted, to implement copying with your own classes, you have to implement one or two methods according to the <NSCopying> protocol.

We now show how you can add a copy method to your Fraction class, which you used extensively in Part I, “The Objective-C Language.” Note that the techniques we describe here for copying ...

Get Programming in Objective-C, Sixth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.