iPhone Programming: Protocols

One of the first topics that gave me pause during my iPhone development stint was the concept of protocols. Protocols are a strange & interesting cross between interfaces and event definitions. In many other languages ( Java, C#, VB.NET, etc… ) when you define an interface, you’re defining a common set of methods that objects must implement if they want to be considered to “implement” a given interface. One of the requirements of implementing an interface is that you must implement every method in the interface, either directly or via a subclass by marking the method as abstract.
Interfaces are use frequently for implementing “event callbacks”. Class A would accept an object, instance of a class implementing Interface B. Class A would then call methods defined by the interface, notifying the passed in object of certain events. Below is a simple example:

public interface MyEventInterface {
EventHappened();
}
public class EventHandler : MyEventInteface {
public void EventHappened() {
// Take some action
}
}
public class EventCaller {
private MyEventInterface _eventInterfaceObject;
public EventCaller( MyEventInterface object ) {
_eventInterfaceObject = object;
}
public void SomeCoolMethod() {
_eventInterfaceObject.EventHappened();
}
}

.NET languages aside, this was a pretty standard way to implement a poor mans event-handling mechanism in your code.

Note: .NET CLR languages like C# & VB.NET support a more formal definition of an event and delegates. These are not the delegates we’re taking about in this post.

Well, in Objective-C, protocols provide a similar function to the above. You basically define a standard set of methods/events, called a protocol, that your class will call. Then, when instances of your class are created, a class implementing your protocol, called a ‘delegate’, can register itself as a handler. Take the following protocol definition below:

@protocol MyProtocolDefinition
@required
- (void) Save:(NSString*) stringToSave;
@optional
- (void) OptionalMethod:(NSString*) parameter;
@end

The above code indicates that the Save() method is a required method to implement in classes implementing this protocol. However, the OptionalMethod is optional, meaning classes wanting to use this protocol only need to implement the Save() method, but they could also implement the OptionalMethod. It’s a pretty interesting concept and very powerful.
The iPhone SDK is built on protocols and delegates, which makes this concept critical to understanding how to hook into various parts of the iPhone SDK. In fact, when you create a blank Cocoa Touch project in XCode, the first class you’ll see is a AppDelegate.m file. Make sure to check out the Apple Objective-C Tutorial PDF for more information.