May 5, 2021

Forward declaring protocols

Let's talk about header files today in Objc. It is wise to always prefer forward declaring your types in .h file

  1. Sometime to avoid circular dependencies
  2. It is always better for incremental build

The related wiki page list benefits clearly

  • reduce the number of files opened by #include (hence the number of operating system calls)
  • reducing the volume of the pre-processed files (as the header is not included)
  • reducing recompilation impact when the forward declared class is modified.

Forward declaration is possible when compiler don't need to know the structure (properties inside) but only name e.g. types used in a method signature.

Let's see this code.

#import "SomeProtocol.h" // Forward declration will produce compliation error

@interface SomeObject: NSObject<SomeProtocol>

Here as SomeObject is conforming to SomeProtocol It is not possible to forward declare the protocol as it became "part" of SomeObject and compiler need to see the SomeProtocol definition when compiling any file that includes SomeObject.h to

Now the purpose of conforming SomeObject to SomeProtocol most likely will be that some part of the code is passing an instance of SomeObject to somewhere as SomeProtocol type.

If it is the case and you want to still forward declare your protocol (it is better, we know), you can use this nice tip.

@protocol "SomeProtocol.h" // Forward declration will work now

@interface SomeObject: NSObject
- (id<SomeProtocol>) asSomeProtocol // This make possible to use instance of SomeObject as SomeProtocol

So still we were able to forward declare the protocol and also can call asSomeProtocol on instance of SomeObject to pass it as type SomeProtocol.

Share this article
Tagged with: