Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward Class and Protocols in Objective C

I have two classes where both of them have protocols to be implemented.

Can I implement one of the class's protocol in to the other and vice versa?

Does this cause any run time error?

like image 790
shebelaw Avatar asked Feb 03 '26 22:02

shebelaw


1 Answers

Your problem is cyclic dependencies. Forward declaring won't really help either as you'll just get the compiler warning you that it can't see the definitions of the protocols. There are two options:

Option 1

Split the protocols out into their own header files:

ClassA.h:

#import <Foundation/Foundation.h>
#import "ClassBProtocol.h"

@interface ClassA : NSObject <ClassBProtocol>
@end

ClassB.h:

#import <Foundation/Foundation.h>
#import "ClassAProtocol.h"

@interface ClassB : NSObject <ClassAProtocol>
@end

ClassAProtocol.h:

#import <Foundation/Foundation.h>

@protocol ClassAProtocol <NSObject>
...
@end

ClassBProtocol.h:

#import <Foundation/Foundation.h>

@protocol ClassBProtocol <NSObject>
...
@end

Option 2

If you don't care about declaring externally that you implement the protocols, then you could use the class continuation category:

ClassA.h:

#import <Foundation/Foundation.h>

@interface ClassA : NSObject
@end

ClassA.m:

#import "ClassA.h"
#import "ClassB.h"

@implementation ClassA () <ClassBProtocol>
@end

@implementation ClassA
@end

ClassB.h:

#import <Foundation/Foundation.h>

@interface ClassB : NSObject
@end

ClassB.m:

#import "ClassB.h"
#import "ClassA.h"

@implementation ClassB () <ClassAProtocol>
@end

@implementation ClassB
@end
like image 183
mattjgalloway Avatar answered Feb 06 '26 13:02

mattjgalloway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!