Apr 26 2009
Introduction to Protocols
What follows is a quick introduction to working with protocols. This is good background information to understand as protocols are common in various Cocoa frameworks. A protocol is means to define a list of required and/or optional methods that a class implements. If a class adopts a protocol, it must implement all required methods in the protocols it adopts.
Cocoa uses protocols to support interprocess communication through Objective-C messages. In addition, since Objective-C does not support multiple inheritance, you can achieve similar functionality with protocols, as a class can adopt more than one protocol.
A good example of a protocol is NSCoding, which has two required methods that a class must implement. This protocol is used to enable classes to be encoded and decoded, that is, archiving of objects by writing to permanent storage.
@protocol NSCoding - (void)encodeWithCoder:(NSCoder *)aCoder; - (id)initWithCoder:(NSCoder *)aDecoder; @end
To adopt a protocol, enclose the name of the protocol in <> as below:
// Interface @interface SomeClass : NSObject <NSCoding> { ... } // Implementation @implementation SomeClass -(void)encodeWithCoder:(NSCoder *)aCoder { ... } -(id)initWithCoder:(NSCoder *)aDecoder { ... }
Defining a Protocol
You can create both required an optional methods within a protocol. What follows is a definion of a protocol named ‘Fubar’:
@protocol Fubar - (BOOL)send:(id)data; - (id)receive; @optional - (int)status; @end
To use the protocol, as with the example above, specify the protocol in the interface and write the required methods in the class implementation:
// Interface @interface AnotherClass : NSObject <Fubar> { ... } // Implementation @implementation AnotherClass - (BOOL)send:(id)data { ... } - (id)receive { ... } // Optional methods - (int)status { ... } @end
If you are from a Java background, protocols should look familiar as they are analogous to an interface.
Tips by RSS
Tips by Email
thank you very much!!! the best explanation so fur about this subject!!
I spend hour looking for this information everywhere!!
but you made it a piece of cake for me!
thanks
Nice tutorial…really awesome