objective-c - 使用@class 访问委托(delegate)协议(protocol)声明

标签 objective-c import header-files forward-declaration objective-c-protocol

我读到你应该尝试在你的头文件中使用 @class 而不是 #import 但这在你的 @class 时不起作用 包含您尝试使用的委托(delegate)协议(protocol)。

MyView.h

#import <UIKit/UIKit.h>
@class MyCustomClass;  // <-- doesn't work for MyCustomClassDelegate, used below

@interface MyView : UIView <MyCustomClassDelegate>

@end

我想我忽略了一些东西,有没有办法让 @class 在这种情况下工作,或者 #import 是我唯一的选择?

编辑:解决此问题的一个方法当然是在 .m 文件的私有(private)接口(interface)部分而不是 .h 文件中声明您的#import MyCustomClass 和 MyCustomClassDelegate。

最佳答案

如果你只需要像这样的变量,你可以使用@protocol来转发声明一个协议(protocol):

@protocol MyProtocol;

@interface MyClass {
    id<MyProtocol> var;
}
@end

在您的情况下,声明的类正在尝试遵守协议(protocol),因此编译器此时必须了解协议(protocol)方法,以便推断天气是否符合该类。

在这种情况下,我认为您的选择是将协议(protocol)拆分到它自己的文件和 #import header 中,或者在使用它的类声明上方的 header 中声明协议(protocol)。

关于objective-c - 使用@class 访问委托(delegate)协议(protocol)声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19499849/

相关文章:

c++ - 给定源文件的 header "corresponding"是否有技术名称?

objective-c - NSTableView 和 NSMutable Array 不链接

objective-c - 使用表示变量名称的字符串来设置变量

ios - 静态 UITableView Cell 属性修改

objective-c - 如何在iOS中本地播放.ts(传输流)文件

mysql - 将SQL文件导入mysql

Javascript动态导入设置图像

python - 在python中导入错误

c++ : Receiving a lot of errors. 简单继承导致大量错误

c++ - 在 ';' 之前缺少 'template<'