像@class一样声明协议

9

我有两个协议正在互相通信。它们在同一个文件中定义。

@protocol Protocol1 <NSObject>
-(void)setProtocolDelegate:(id<Protocol2>)delegate;
@end

@protocol Protocol2 <NSObject>
-(void)protocol:(UIViewController<Protocol1>*)anObject chosenElementAtIndex:(NSInteger)aIndex;
@end

如何声明一个空协议Protocol2,只是让编译器知道它稍后会被声明?
如果Protocol2是一个类,我会在之前写上@class Protocol2;
@class Protocol2;
@protocol Protocol1 <NSObject>
-(void)setProtocolDelegate:(Protocol2*)delegate;
@end

@interface Protocol2 <NSObject>
-(void)protocol:(UIViewController<Protocol1>*)anObject chosenElementAtIndex:(NSInteger)aIndex;
@end

协议的类似结构是什么?

2个回答

13

使用 @protocol 来进行协议的前向声明:

@protocol Protocol2;
@protocol Protocol1 <NSObject>
-(void)setProtocolDelegate:(id<Protocol2>)delegate;
@end

@protocol Protocol2 <NSObject>
-(void)protocol:(UIViewController<Protocol1>*)anObject chosenElementAtIndex:(NSInteger)aIndex;
@end

1
你的问题是使用了 @class 关键字来进行协议的前向声明。 应该使用 @protocol。

我知道它不应该是@class。我使用第二个片段来展示与类的类比,以使问题更清晰。无论如何,感谢您的帮助。 - Michał Zygar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接