Chapter 11: Protocols In Objective-C

Matthew Campbell, December 11, 2011

A protocol is a way to require classes to implement a set of methods. We define a protocol much like a class or a category, it is essentially a list of methods. Protocols do not do anything themselves, they are a definition of a type of contract that we can require other classes to implement.

We call that adopting the protocol and we’ve seen this before. You may recall that the application delegate file that XCode created for use included this as part of the application delegate interface:

<UIApplicationDelegate>

This was required because we needed our class to act as an application delegate. This delegation pattern is implemented using protocols because we need a way to require a class to implement a set of methods in order for it to act as a delegate. The code above is how you indicate to the system that a class is adopting a protocol.

How to Define a Protocol

To define a protocol you need a separate header file. You can get one of these by right clicking your group folder and selecting New > New File… > C and C ++ > Header File. Then you simply start the protocol definition using the @protocol keyword:

#import <Foundation/Foundation.h>
@protocol ImplementIt
@end

As you can see it works like a class definition. All you need to do now is fill in what methods you want to be part of the protocol. I want my ImplementIt protocol to require my classes to return three strings that would be used in HTML documents:

#import <Foundation/Foundation.h>
@protocol ImplementIt
- (NSString *) header;
- (NSString *) title;
- (NSString *) paragraph;
@end

That is all there is too it and this looks just like an interface definition. If I want to have a class adopt my protocol all I need to do is add &*lt;ImplementIt> to the interface definition and import the header file. Of course, now I will be required to implement the three methods above or XCode will report an error.

Here is how I did this for myClass:

Interface:

#import <Foundation/Foundation.h>
#import "ImplementIt.h"
@interface myClass : NSObject<ImplementIt>
[CODE OMITTED HERE]
@end

Implementation:

#import "myClass.h"
@implementation myClass
@synthesize name, number;
[CODE OMITTED]
//Implementing ImplementIt protocol
- (NSString *) header{
      return @"<h1>Header Text</h1>";
}
- (NSString *) title{
      return @"<title>Title Text</title>";
}
- (NSString *) paragraph{
      return @"<p>Paragraph Text</p>";
}
@end

That is all there is to it. If you have not done much object oriented programming and are confused about why you would need to use protocols don’t worry about it right now. This technique solves a problem that you probably just have not dealt with yet. The key thing to remember for now is that protocols are what is required to make delegation work and delegation is used frequently in iPhone programming.