Protocols in Objective-C

Ever since I started learning Objective-C, I always thought the concept of “Protocols” was identical to that of Interfaces in Java. Today, after reading this page, I understood that actually Interfaces in Java are based on Objective-C protocols.

How do protocols work in Objective-C?

A protocol allows us to define a series of messages that objects must respond to in order to claim that they “conform” to it. the concept is extremely similar to Java’s, with a couple of exceptions. Let’s take a look at a practical example of how protocols work in Objective-C.

What we’ll do is define a “Hello” protocol that requires responding to a message “sayHello”. Then, we’ll declare a class that conforms to this protocol.

File that defines the protocol, hello.h:

@protocol Hello
- (void) sayHello;
@end

The implementation of the protocol in a “HelloWorld” class. File hellowworld.h

#import  //Solo en Mac!
#import 
#import "hello.h"

@interface Hello : NSObject {
}

- (void)sayHello;

@end

File helloworld.m:

#import "helloworld.h"

@implementation HelloWorld

- (void)sayHello
{
    printf("Hello, World!\n");
}

@end

Next, we include everything in a file main.m to test the protocol:

#import "helloworld.h"

int main(int argc, char* argv[])
{
    id hello = [[HelloWorld alloc] init];

    [hello sayHello];

    [hello release];

    return 0;
}

As you can see, protocols work in a very similar fashion to Java Interfaces.

If you look closely into this last file notice I never declared that it conforms to the Hello protocol. The Objective-C runtime is responsible for determining if the instance is capable of responding to the sayHello message. What’s interesting here is that I could send this message even if the Hello protocol didn’t exist. This case is what’s called an “informal protocol”.

An informal protocol is just like a regular protocol, except the protocol is never formally declared. It’s rather more of a convention. This is the first difference between Objective-C protocols and Java interfaces. In Java, it’s not possible to to invoke the method of an object if this object does not belong to a type that declares such method.

The other difference between Objective-C protocols and Java interfaces is that a protocol can specify “optional” messages. These don’t need to be implemented by the classes that conform to the protocol.

To declare an optional message we simply add the keyword @optional “on top” of the optional messages in the header that defines the protocol. For example:

// somewhere in hello.h:
    @optional
    - (void)sayGoodbye; //Goodbye is an optional method of the protocol

I never would’ve imagined that the direction in which the inspiration for these similar concepts between languages would’ve been from Objective-C to Java. Sometimes it’s interesting to read the history behind programming languages.