Nếu bạn muốn chạy trên các phiên bản cũ của hệ điều hành Mac OS X hoặc bạn đang làm phát triển iPhone, bạn sẽ muốn đọc toàn bộ giống như những con chim và những con ong ra ở đây trong thế giới thực, các đối tượng bên trong một chương trình có một vòng đời. Chúng ta được sinh ra (thông qua một alloc hoặc mới), | 236 CHAPTER 13 Protocols Why would you want to create or adopt a formal protocol It sounds like a lot of work is required to implement every method. Depending on the protocol some busywork may even be involved. But more often than not a protocol has only a small number of methods to implement and you have to implement them all to gain a useful set of functionality anyway so the formal protocol requirements are generally not a burden. Objective-C has added some nice features that make using protocols much less onerous which we ll talk about at the end of this chapter. Declaring Protocols Let s take a look at a protocol declared by Cocoa NSCopying. If you adopt NSCopying your object knows how to make copies of itself protocol NSCopying - id copyWithZone NSZone zone end The syntax looks kind of the same as the syntax for declaring a class or a category. Rather than using interface you use protocol to tell the compiler I m about to show you what a new formal protocol will look like. That statement is followed by the protocol name. Protocol names must be unique. Next is a list of method declarations which every protocol adopter must implement. The protocol declaration finishes with end. There are no instance variables introduced with a protocol. Let s look at another example. Here s the NSCoding protocol from Cocoa protocol NSCoding - void encodeWithCoder NSCoder aCoder - id initWithCoder NSCoder aDecoder end When a class adopts NSCoding that class promises to implement both of these messages. encodeWithCoder is used to take an object s instance variables and freeze-dry them into an NSCoder object. initWithCoder extracts freeze-dried instance variables from an NSCoder and uses them to initialize a new object. These are always implemented as a pair there s no point in encoding an object if you ll never revive it into a new one and if you never encode an object you won t have anything to use to create a new one. CHAPTER 13 Protocols 237 Adopting a Protocol To adopt a