Jump to content

How to use protocols in Objective-c

+ 3
  Doron Katz's Photo
Posted Jul 19 2010 02:08 PM

Protocols are a way of enforcing certain methods to be utilized, regardless of the actual class the object is part of, thus ensuring that a certain form of method template is implemented. Basically, a way of declaring an interface to an object while concealing it's class. This is why we write a protocol in a similar way to how we would write an interface declaration.

You can relate two different objects by confirming to a protocol, and rather than having to inherit from a superclass whereby you are required to have the two objects relate to each other, you can just concentrate on a list of methods that will makeup the protocol without having to think about the concrete class and type of class that will make use of it. Okay so let's put this concept into code:

@protocol automobile <NSObject>
 -(NSString *) steeringWheelType; 
 -int numberOfWheels; 

 -(NSString *) countryOfOrigin; 

So the code above describes the methods that a class should utilise, which ones are mandatory and which ones are optional, if you were to comply with such a protocol. So to use this protocol in your classes:

@interface Mercedes : NSObject <automobile> 
 @property (nonatomic, retain) NSString * steeringWheelType; 
 @property (nonatomic) int numberOfWheels; 
 // we don't have to implement countryOfOrigin

A protocol can of course incorporate other protocols that have been defined similarly to how it is done with inheritance, without any hierarchy imposed on protocols (unlike subclassing).

@protocol Bike <Automobile, BMW>

And that's it. I will also offer a brief introduction into Categories in a later O'Reilly 'Answers' post.

1 Subscribe

0 Replies