我有两个RLMObject
名为RCRealmUser
和RCRealmLocation
。 RCRealmUser
在RCRealmLocation
上定义了一对一关系,RCRealmLocation
与RCRealmUser
呈反比关系。这就是我如何定义这两个:
RCRealmUser.h
@interface RCRealmUser : RLMObject
@property NSNumber <RLMInt> *userId;
@property NSString *username;
@property NSNumber <RLMInt> *countryCode;
@property NSNumber <RLMDouble> *phoneNumber;
@property NSString *fullName;
@property NSString *profileImageURL;
@property RCRealmLocation *location;
- (id)initWithMantleModel:(RCUserProfile *)user;
@end
RLM_ARRAY_TYPE(RCRealmUser)
RCRealmUser.m
@implementation RCRealmUser
+ (NSString *)primaryKey {
return @"userId";
}
+ (NSArray *)indexedProperties {
return @[@"fullName"];
}
+ (NSDictionary *)defaultPropertyValues {
return @{@"countryCode": @91};
}
- (id)initWithMantleModel:(RCUserProfile *)user {
self = [super init];
if(!self) return nil;
self.userId = user.userId;
self.username = user.username;
self.countryCode = user.countryCode;
self.phoneNumber = user.phoneNumber;
self.fullName = user.fullName;
self.profileImageURL = user.profileImageURL.absoluteString;
self.location = [[RCRealmLocation alloc] initWithMantleModel:user.location];
return self;
}
@end
RCRealmLocation.h
@interface RCRealmLocation : RLMObject
@property (readonly) RLMLinkingObjects *userId;
@property NSNumber <RLMDouble> *latitute;
@property NSNumber <RLMDouble> *longitude;
@property NSDate *timestamp;
@property NSNumber <RLMInt> *accuracy;
- (id)initWithMantleModel:(RCLocation *)location;
@end
RLM_ARRAY_TYPE(RCRealmLocation)
RCRealmLocation.m
@implementation RCRealmLocation
+ (NSArray<NSString *> *)indexedProperties {
return @[@"timestamp"];
}
+ (NSDictionary<NSString *,RLMPropertyDescriptor *> *)linkingObjectsProperties {
return @{@"userId": [RLMPropertyDescriptor descriptorWithClass:RCRealmUser.class propertyName:@"userId"]};
}
- (id)initWithMantleModel:(RCLocation *)location {
self = [super init];
if(!self) return nil;
self.latitute = location.latitute;
self.longitude = location.longitude;
self.timestamp = location.timestamp;
self.accuracy = location.accuracy;
return self;
}
现在当我尝试插入RCRealmUser
时遇到错误
&#39; RLMException&#39;,原因:&#39;架构验证因以下原因而失败 错误:
- Property&#39; userId&#39;声明为链接对象属性的来源&quot; userId&#39;不是链接。&#39;
我在某处做错了吗?
答案 0 :(得分:0)
“链接对象”属性必须表示链接(关系)。
在您的情况下,您说RCRealmLocation.userId
属性应该代表通过其RCRealmUser
属性链接到该位置的userId
个对象。但是,RCRealmUser.userId
与RCRealmLocation
个对象不是关系,它是一个可选的整数。
我相信你想要的是RCRealmLocation
上的一个属性,该属性引用链接到该位置的所有RCRealmUser
及其locations
关系。您可以通过将RCRealmLocation.userId
属性更改为此来完成此操作:
@property (readonly) RLMLinkingObjects *users;
以及您对linkingObjectsProperties
的实施:
return @{@"users": [RLMPropertyDescriptor descriptorWithClass:RCRealmUser.class propertyName:@"location"]};