Objective-C Protocol Forward Declarations Objective-C Protocol Forward Declarations objective-c objective-c

Objective-C Protocol Forward Declarations


You cannot forward declare a superclass or a protocol that it conforms to. In those cases, you must include the header. This is because (in the case of superclass) the superclass's instance variables and methods become part of your class; or (in the case of protocols) the protocol's methods become methods declared in your class, without needing to declare them explicitly. (i.e. Now other people who include your class's header will see that your class declares those methods, as if you declared them yourself.) The only way that that could be possible is if they were already defined in this scope, i.e. their headers are imported.

#import <SomeClass.h>#import <SomeProtocol.h> // these two must be imported@interface MyClass : SomeClass <SomeProtocol>@end

Forward declarations are useful for things that just show up in the type of a variable (specifically, an object pointer variable). Object pointers are all the same size and there is no difference between different types of object pointers at runtime (the concept of type of object pointer is just a compile-time thing). So there is no real need to know exactly what's in the classes of those types. Thus they can be forward declared.

@class SomeClass;@protocol SomeProtocol; // you can forward-declare these@interface MyClass {    SomeClass *var1;    id<SomeProtocol> var2;}@end


Yes you are correct that all of the files will need to be recompiled, but this is necessary. Files that import the class header need to know the methods associated with the protocol it implements. If you tuck that definition away in the .m file then it is only visible to one file (since .m files never get imported). It's not the same as forward declaring classes. If you forward declare a protocol, you must declare it somewhere that is visible in the same scope as the forward declaration. I can't think of any example where this doesn't occur in the same file.

In ARC this is an error, because ARC needs to know about the memory management of the declared methods (do they return +1 instances, internal pointers, etc?)


By declaring your class in MyClass.h, you have to import all header files for its superclass as well as protocols it adopted in the MyClass.h file. Protocols in Objective-c is considered as a variant type of inheritance.

Forward declarations are usually used in class' member declaration .