我的简单 iOS objective-c 应用程序有两个相互链接的 .h 文件。一个是 Delegate Protocol
,另一个是定义 NS_ENUM
的类的 Interface
。
这是界面文件(HistogramView.h):
#import <UIKit/UIKit.h>
#import "DiagramViewDataSource.h"
#import "DiagramViewDelegate.h"
typedef NS_ENUM(NSInteger, MoveOperation) {
MOVE_BACKWARD,
MOVE_FORWARD
};
@interface HistogramView : UIView
@property (weak) id <DiagramViewDelegate> delegate;
@property (weak) id <DiagramViewDataSource> dataSource;
@end
这是委托(delegate)协议(protocol) (DiagramViewDelegate.h):
#import <Foundation/Foundation.h>
#import "HistogramView.h"
@protocol DiagramViewDelegate <NSObject>
-(void)diagramSectionChangedWithOperation:(MoveOperation)op;
@end
在委托(delegate)中,编译器向我显示了一个链接到 MoveOperation
参数的错误:"Expected a type"。我还尝试通过这种方式在 @protocol
之前添加 @class HistogramView
:
#import <Foundation/Foundation.h>
#import "HistogramView.h"
@class HistogramView;
@protocol DiagramViewDelegate <NSObject>
-(void)diagramSectionChangedWithOperation:(MoveOperation)op;
@end
但没有任何变化。你能帮助我吗?提前谢谢你。
最佳答案
三个选项:
删除
HistogramView.h
中的#import "DiagramViewDelegate.h"
和@interface
转发声明协议(protocol)使用@protocol DiagramViewDelegate
。提供前向声明来解决循环问题,它们通常在两个类相互依赖时使用(如@class classname;
)将
HistogramView.h
中的#import "DiagramViewDelegate.h"
移动到typedef
之后>。这可能看起来有点“hacky”,但直接观察到DiagramViewDelegate.h
需要enum
并导致...将枚举移动到它自己的标题中,并包含在
DiagramViewDelegate.h
和HistogramView.h
中。这是执行 (2) 的“更简洁”方法 - 即安排编译器读取的订单项。
HTH
关于objective-c - 解决循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27495364/