11.5 Protocol definitions

In Objective-C, protocols play the role that interfaces play in Object Pascal, but there are some differences:

Objective-C classes can indicate which protocols they implement in the class definition, as could be seen in the syntax diagram for Objective-C classes.

The following diagram shows how to declare a protocol. It starts with the objcprotocol keyword:

_________________________________________________________________________________________________________
Protocol type

 --objcprotocol--------------------------------------------
               -external--|---------------------|-heritage|
                         -name -string constant-
----protocol method list--end ----------------------------------------

--heritage -(---protocol type identifier--) -----------------------------
             ---------, ---------|

--                ---------------             ------------------
  protocol method list | -required -|  method definition  |
                   | -optional-|                  |
                   ------------------------------|
___________________________________________________________________

As in the case of objective-Pascal classes, the external specifier tells the compiler that the declaration is an import of a protocol defined elsewhere. For methods, almost the same rules apply as for methods in the Objective-Pascal class declarations. The exception is that message specifiers must be present.

The required and optional specifiers before a series of method declarations are optional. If none is specified, required is assumed. The following is a definition of a protocol:

type  
  MyProtocol = objccprotocol  
    // default is required  
    procedure aRequiredMethod;  
      message ’aRequiredMethod’;  
  optional  
    procedure anOptionalMethodWithPara(para: longint);  
      message ’anOptionalMethodWithPara:’;  
    procedure anotherOptionalMethod;  
      message ’anotherOptionalMethod’;  
  required  
    function aSecondRequiredMethod: longint;  
      message ’aSecondRequiredMethod’;  
  end;  
 
  MyClassImplementingProtocol = objcclass(NSObject,MyProtocol)  
    procedure aRequiredMethod;  
    procedure anOptionalMethodWithPara(para: longint);  
    function aSecondRequiredMethod: longint;  
  end;

Note that in the class declaration, the message specifier was omitted. The compiler (and runtime) can deduce it from the protocol definition.