Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

13. Protocols

A protocol is a defined set of methods that a class can choose to implement. Protocols are useful when an object needs to talk to one or more other objects but doesn’t know (or particularly care) the class of those other objects. Objective-C protocols are the equivalent of Java interfaces. In fact, the designers of Java borrowed the concept from Objective-C. Protocols are used throughout the Cocoa frameworks. Objective-C has both formal and informal protocols. A formal protocol declares a set of required methods and perhaps some optional methods. A class can then adopt the protocol by implementing all the protocol’s required methods. When a class declares that it adopts a formal protocol, the compiler checks to see that the class implements all the protocol’s required methods. An informal protocol is merely a list of method declarations in a category header that a class could choose to implement. Most uses of informal protocols in the Cocoa frameworks are being replaced by formal protocols.

In this chapter, you will learn when to use a formal protocol, how to declare a formal protocol, and how to code a class that adopts a formal protocol. The chapter then goes through a complete example, a TablePrinter class. A TablePrinter object can print data from another object in the form of a table. A TablePrinter does not need to know the class of the object that is supplying the data. The only thing a TablePrinter needs to know is that the object supplying its data belongs to a class that adopts the TablePrinterDataSource formal protocol.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint