RLMLinkingObjects 循环依赖

RLMLinkingObjects circular dependency

我遇到循环依赖的问题:当使用新的 RLMLinkingObjects 建立反向关系时,我收到以下错误:

Type argument 'RCon *' does not satisfy the bound ('RLMObject *') of type parameter 'RLMObjectType'

我有两个 classes RCon 和 RSan。 RCon对RSan有多个引用,RSan又被多个RCon引用,所以是多对多的关系。 以下是 classes.

的声明示例

第一个class:

//  RSan.h

#import <Realm/Realm.h>
#import <UIKit/UIKit.h>

@class RCon;

@interface RSan : RLMObject
@property (readonly) RLMLinkingObjects<RCon*>* cons;
@end
RLM_ARRAY_TYPE(RSan)

另一个class:

//  RCon.h

#import <Realm/Realm.h>
#import <UIKit/UIKit.h>
#import "RSan.h"

@interface RCon : RLMObject
@property RLMArray<RSan*><RSan>* sans;
@end
RLM_ARRAY_TYPE(RCon)

这是由于 Objective-C 编译器的限制。 RLMArray 的通用约束需要它们的元素应该是 RLMObject 的子 class。但是 Objective-C 编译器无法从 @class 转发的声明中识别它。

要解决这个问题,我认为唯一的方法是在同一个文件中声明两个 @interface,然后使用 class 扩展名声明它们的属性。像下面这样:

#import <Realm/Realm.h>
#import <UIKit/UIKit.h>

@interface RCon : RLMObject
@end
RLM_ARRAY_TYPE(RCon)

@interface RSan : RLMObject
@end
RLM_ARRAY_TYPE(RSan)

@interface RCon()
@property RLMArray<RSan*><RSan>* sans;
@end

@interface RSan()
@property (readonly) RLMLinkingObjects<RCon*>* cons;
@end

注意:所有 avobe 代码应在同一个文件中。