Introduction to Protocols

Fri, Apr 26

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.

3 comments

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

by Fernando on May 25, 2011. Reply #

Nice tutorial…really awesome

by Vipin on Sep 7, 2011. Reply #

Good explanation. For C++’ers required protocol methods are like pure virtual methods.

by Dave Smith on Jun 20, 2012. Reply #

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>