解决循环依赖

sup*_*cio 2 enums objective-c circular-dependency

我的简单的iOS objective-c应用程序我有两个.h文件相互链接.一个是a Delegate Protocol,另一个是Interface用于定义一个类的类NS_ENUM.

这是接口文件(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 
Run Code Online (Sandbox Code Playgroud)

这是委托协议(DiagramViewDelegate.h):

#import <Foundation/Foundation.h>
#import "HistogramView.h"

@protocol DiagramViewDelegate <NSObject>

-(void)diagramSectionChangedWithOperation:(MoveOperation)op;

@end
Run Code Online (Sandbox Code Playgroud)

在委托中,编译器显示链接到MoveOperation参数的错误:"预期类型".我也尝试添加@class HistogramView之前@protocol是这样的:

#import <Foundation/Foundation.h>
#import "HistogramView.h"

@class HistogramView;

@protocol DiagramViewDelegate <NSObject>

-(void)diagramSectionChangedWithOperation:(MoveOperation)op;

@end 
Run Code Online (Sandbox Code Playgroud)

但没有变化.你能帮助我吗?先感谢您.

CRD*_*CRD 5

三种选择:

  1. 删除#import "DiagramViewDelegate.h"in HistogramView.h@interfaceforward 之前使用声明协议@protocol DiagramViewDelegate.提供前向声明以解决循环,它们通常在两个类相互依赖时使用(如@class classname;)

  2. 移动#import "DiagramViewDelegate.h"HistogramView.htypedef.这可能看起来有点"hacky",但直接观察到enum需要DiagramViewDelegate.h并导致......

  3. 将枚举移动到自己的标题中并包含在两个DiagramViewDelegate.h和中HistogramView.h.这是"更清洁"的方式(2) - 即安排订单项将由编译器读取.

HTH

  • 选项4:将`enum`声明移动到DiagramViewDelegate.h.但选项3是最好的. (2认同)