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?
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:
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With