问题描述
First, I have seen this question as well as this, but my problem is not addressed there.
我在自己的头文件中定义了协议ProtocolA
.然后,我有两个ClassA
和ClassB
类别,它们都符合该协议,因此协议头文件被导入了它们的头文件中.
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.
现在,它变得有点复杂了. ClassA
在第三个ClassC
中使用(因此被导入).此类符合第二个协议ProtocolB
.该协议还具有其自己的头文件,在其中使用和导入ClassB
.因此,我的ClassC
(直接或间接)导入了ClassA
和ClassB
(都导入了ProtocolA
).这给了我关于ProtocolA
的以下警告:
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
为什么会这样?据我了解,#import
宏是完全为避免我们在#include
中遇到的此类问题而发明的.如何在不使用包含保护的情况下解决问题?我真的无法删除任何导入.
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.
这是说明情况的代码:
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
推荐答案
不要在ProtocolB
标头中导入ClassB
,只需在其中使用@class ClassB;
并删除#import "ClassB"
do not Import ClassB
in ProtocolB
header, just use @class ClassB;
in it and remove #import "ClassB"
这篇关于协议定义重复警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!