Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend


In Objective-C, protocols are sets of messages that a class implements. You can specify that a pointer should refer to a class implementing a given interface:

id<AnInterface> object;
NSString<AnInterface> *string;

The first example is the equivalent of declaring the variable as the type of an interface in Java. In C++, the closest equivalent is to use abstract classes instead of interfaces and specify the abstract class as the type.

The second example is more interesting. The string variable is allowed to be any NSString subclass that implements AnInterface, which allows you to restrict a type to a subset of subclasses that implement a particular interface. A common example is something like the following:

NSObject<MyDelegateProtocol> *delegate;

This allows it to be any subclass of NSObject (and so the methods you generally expect from any object will work), and additionally requires it to implement the specified protocol. Here's an alternative:

id <NSObject, MyDelegateProtocol> delegate;

This works for NSObject, because NSObject is both a class and a protocol, with the class adopting the protocol. This was done so NSProxy and other root classes can be used interchangeably with NSObject subclasses.

Because Objective-C comes from Smalltalk, with the "everything is an object" mentality, it shouldn't be a surprise that protocols, like classes, are also objects. As such, you can send them messages to perform introspection. Typically, you don't do this yourself, instead relying on messages sent to NSObject subclasses:

if ([object conformsToProtocol:@protocol(MyDelegateProtocol)])
  // Do something with the delegate

One thing that's slightly confusing about protocols is the fact that they're tested for equality simply by comparing their names. If you have two protocols with the same name, you have no way of telling, at runtime, which one an object implements. The reasoning was to allow testing for conformance using the @protocol() directive as shown above in source files that don't have access to the protocol description, but it can cause confusion.

  • + Share This
  • 🔖 Save To Your Account