为什么代码无法避免循环引用?

Why the code does not work to avoid Circular References?

我正在编译代码以避免保留循环,当我使用 weak 时,出现此错误:1. property of weak attribute must be of object type2. Unknown type name 'OrderEntry'。代码有什么问题?谢谢!

// OrderEntry.h
#import <Foundation/Foundation.h>
#import "OrderItem.h"
#import "Address.h"

@interface OrderEntry : NSObject

 @property (strong, nonatomic)OrderItem *orderItem;
 @property (strong, nonatomic)Address *shippingAddress;
 @property (strong, nonatomic) NSString *orderID;

@end


// OrderItem.h
#import <Foundation/Foundation.h>
#import "OrderEntry.h"


@interface OrderItem : NSObject

 @property (strong,nonatomic) NSString *name;

 @property (weak, nonatomic) OrderEntry *entry;

 @end

问题在于两个 .h 文件相互包含。这会导致对声明的循环依赖。简单的解决方案是改用前向声明。

OrderEntry.h:

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

@class OrderItem;

@interface OrderEntry : NSObject

 @property (strong, nonatomic) OrderItem *orderItem;
 @property (strong, nonatomic) Address *shippingAddress;
 @property (strong, nonatomic) NSString *orderID;

@end

OrderItem.h:

#import <Foundation/Foundation.h>

@class OrderEntry;

@interface OrderItem : NSObject

 @property (strong, nonatomic) NSString *name;
 @property (weak, nonatomic) OrderEntry *entry;

@end

然后将.h 文件导入到.m 文件中。

一般准则是在另一个 .h 文件中导入尽可能少的 .h 文件。尽可能使用 类 和协议的前向声明。