Search code examples
iosclassprotocolsforward-declaration

Forward declaration for classes called within method arguments of a protocol definition


Forward declarations are used to reduce dependencies and prevent unnecessary imports where multiple header files are involved.

This being said, how should I go about this scenario?

Let's say I have the following:

ClassAlpha.h

@interface ClassAlpha: NSObject

-(void)helloWorld;

@end

ProtocolA.h

@protocol ProtocolA <NSObject>

-(void)doSomethingWithAlpha:(ClassAlpha *__Nonnull)alpha;

@end

ClassBeta.h (conforms to ProtocolA)

@interface ClassBeta: NSObject<ProtocolA>

@end

ClassBeta.m

#import "ClassAlpha.h"

@implementation ClassBeta

-(void)doSomethingWithAlpha:(ClassAlpha *)alpha
{
    NSLog(@"Hello");
}
@end

In ProtocolA.h, should I use a forward declaration of ClassAlpha? However, if I were to do so, that would mean that ClassBeta would have to be the one that imports ClassAlpha within its implementation, alongside importing ProtocolA. Alternatively, if I were to use the import statement of ClassAlpha within ProtocolA, needless to say ClassBeta woudldn't need to do so. What would be the best practice for this situation?


Solution

  • You should avoid #import in headers as much as possible. So, yes, you should use a forward declaration of ClassAlpha (i.e. @class ClassAlpha;) in PrototolA.h, because to use ClassAlpha * as a type in a parameter declaration, all you need to know is that ClassAlpha is the name of a class. You don't need to know anything else about how it is declared. Yes, you should import ClassAlpha.h in ClassBeta.m; you should do imports in implementation files as much as possible instead of header files.