2016-05-17 80 views
1

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

回答

2

作为例外说,你需要声明一个协议来定义包含类型RLMArray的。这就是RLM_ARRAY_TYPE宏的功能。这里的特别之处在于,您需要在接口声明之前放置此声明,可以通过预先声明User类型@class来完成此声明。你可以这样说:

#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 
+0

领域文档说,我们应该在模型界面的底部添加宏。 是的,前向声明是除了在顶部添加宏之外的解决方案。谢谢你。 –

1

我认为术语是“逆关系”,我从未试图引用,并用相同的类的嵌套对象对象。 但在Realm纪录片中,他们有一个“狗”和“所有者”的例子。 业主可以有狗,狗可以有业主,他们有一个“反向关系”

它应该是这样的:

@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

+0

我觉得这个解决方案还应该工作基于一个更清晰的例子本文 https://realm.io/news/realm-objc-swift-0.100.0/在 –