Skip to content

Creating a protocol class and inheriting methods from it

Nat! edited this page Apr 7, 2017 · 1 revision

You read mulle_objc: inheriting methods from protocols and you want to try it out. Here's how it works:

MyProtocol.h:

@class MyProtocol;        // this is necessary
@protocol MyProtocol;     // define a protocol
+ (void) hello;
@end

MyProtocol.m:

#import "MyProtocol.h"
#include <stdio.h>

@interface MyProtocol < MyProtocol>  // define a root class of same name
@end                                 // that implements the protocol

@implementation MyProtocol

+ (void) hello
{
   printf( "Hello\n");
}
@end

test.m:

#import "MyProtocol.h"

@interface MyClass < MyProtocol>
@end

@implementation MyClass
@end

int   main( int argc, char *argv[])
{
   [MyClass hello];  // inherited +hello implementation from protocol
   return( 0);
}

In the future there might be a new keyword @protocolclass.

Requirements for a protocolclass

For methods of a protocolclass to be found during method searches of a class, that conforms to that protocol, the following requirements must be met:

  1. The class must conform to the protocol
  2. At the @implementation of the class, it must be known, that the protocolclass of the same name as the protocol exists
  3. The protocolclass must be a root class
  4. The protocolclass must not have instance variables
  5. The protocolclass must conform to its protocol
  6. The protocolclass must not conform to any other protocol