领域模型中的递归关系

Recursive Relationship in Realm Model

如果我希望拥有相同用户模型的Realm 数组,则会发生异常。 RLMException(@"RLMArray properties require a protocol defining the contained type - example: RLMArray<Person>."); 那么有解决方法吗?如何在 Realm 中实现如下递归关系?

#import <Realm/Realm.h>
@interface User : RLMObject
@property NSInteger userId;
@property NSString *displayName;
@property RLMArray<User> *friends;
- (instancetype)initWithDictionary:(NSDictionary *)data;
@end  
RLM_ARRAY_TYPE (User)

我认为术语是 "Inverse Relationships",我从未尝试过使用相同 class 的嵌套对象来引用和对象。 但是在Realm Documentary里面,他们有和"dog"和"owner"的例子。 主人可以养狗,狗可以有主人,它们有一个"Inverse Relationships".

它应该是这样的:

@interface Dog : RLMObject
@property NSString *name;
@property NSInteger age;
@property (readonly) RLMLinkingObjects *owners;
@end

@implementation Dog
+ (NSDictionary *)linkingObjectsProperties {
    return @{
        @"owners": [RLMPropertyDescriptor descriptorWithClass:Person.class propertyName:@"dogs"],
    };
}
@end

参考:https://realm.io/docs/objc/latest/#relationships

如异常所述,您需要声明一个协议来定义 RLMArray 的包含类型。这就是 RLM_ARRAY_TYPE 宏的作用。这里的特殊之处在于您需要将此声明放在接口声明之前,这可以通过使用 @class 预先声明 User 类型来完成。你可以这样做:

#import <Realm/Realm.h>

@class User;
RLM_ARRAY_TYPE (User)

@interface User : RLMObject
@property NSInteger userId;
@property NSString *displayName;
@property RLMArray<User> *friends;
- (instancetype)initWithDictionary:(NSDictionary *)data;
@end