objective-c - 解决循环依赖

标签 objective-c enums circular-dependency

我的简单 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 

但没有任何变化。你能帮助我吗?提前谢谢你。

最佳答案

三个选项:

  1. 删除 HistogramView.h 中的 #import "DiagramViewDelegate.h"@interface 转发声明协议(protocol)使用@protocol DiagramViewDelegate。提供前向声明来解决循环问题,它们通常在两个类相互依赖时使用(如 @class classname;)

  2. HistogramView.h 中的 #import "DiagramViewDelegate.h" 移动到typedef之后>。这可能看起来有点“hacky”,但直接观察到 DiagramViewDelegate.h 需要 enum 并导致...

  3. 将枚举移动到它自己的标题中,并包含在 DiagramViewDelegate.hHistogramView.h 中。这是执行 (2) 的“更简洁”方法 - 即安排编译器读取的订单项。

HTH

关于objective-c - 解决循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27495364/

相关文章:

go - 如何避免循环依赖但保持干净的结构

ios - UIViewTableCell 中的布局 subview 不起作用

ios - 在 iOS 中创建我自己的完成 block

swift - 如何定义一个包含枚举的协议(protocol),该枚举具有它自己定义的值,并且其中一个值存储为属性?

python - 如何处理tastypie中的循环导入

c++ - 多个 Dll 通过 "main"dll 相互调用函数

Objective-C 不同语法问题

ios - NSMutableData-无法识别的选择器发送到实例

java - JOOQ - 未应用内联转换器

c - C 中的枚举声明是什么意思?