Duplicate protocol definition warning

2019-08-08 20:07发布

问题:

First, I have seen this question as well as this, but my problem is not addressed there.

I have a protocol ProtocolA defined in its own header file. Then I have two classes ClassA and ClassB which both conform to this protocol so the protocol-header is imported in their header files.

Now it gets a bit complicated. ClassA is used (and thus imported) in a third ClassC. This class conforms to a second protocol ProtocolB. This protocol also has its own header file where it uses and imports ClassB. So my ClassC imports (either directly or indirectly) both ClassA and ClassB (which both import ProtocolA). This gives me the following warning regarding ProtocolA:

warning: duplicate protocol definition of '…' is ignored

Why is this happening? It was my understanding that the #import macro was invented exactly for avoiding this kind of problems which we had with #include. How can I solve the issue without using an include guard? I can't really remove any of the imports.

EDIT: here is the code to illustrate the situation:

ProtocolA.h

@protocol ProtocolA <NSObject>
- (void)someMethod;
@end

ClassA.h

#import "ProtocolA.h"

@interface ClassA : NSObject <ProtocolA>
...
@end

ClassB.h

#import "ProtocolA.h"

@interface ClassB : NSObject <ProtocolA>
typedef enum Type {
    TypeB1,
    TypeB2
} TypeB;
...
@end

ProtocolB.h

#import "ClassB.h"

@protocol ProtocolB <NSObject>
- (TypeB)someMethod;
@end

ClassC.h

#import "ProtocolB.h"

@interface ClassC : NSObject <ProtocolB>
...
@end

ClassC.m

#import "ClassC.h"
#import "ClassA.h" // the warning appears here

@implementation ClassC
...
@end

回答1:

do not Import ClassB in ProtocolB header, just use @class ClassB; in it and remove #import "ClassB"