我从服务器获取数据列表。他们是各种各样的书籍。我有RLMObjects的书籍,书籍,人。
@class Person, Book;
@interface Person : RLMObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) NSInteger id;
@end
RLM_ARRAY_TYPE(Person)
@interface Book : RLMObject
@property (nonatomic, strong) Person *author;
@property (nonatomic, strong) NSString *price;
@property (nonatomic, strong) RLMArray<Person> *translators;
@end
RLM_ARRAY_TYPE(Book)
@interface Books : RLMObject
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, strong) NSString *year;
@property (nonatomic, strong) RLMArray<Book> *books;
@end
@implementation Person
+ (NSString *)primaryKey {
return @"id";
}
@end
当我获得一系列书籍时,将它们从词典转到Books对象。然后将其添加到领域。
[[RLMRealm defaultRealm] transactionWithBlock:^{
[[RLMRealm defaultRealm] addObject:[Books mj_objectWithKeyValues:responseObject]];
} error:nil];
它崩溃了。因为那里有两本翻译相同的书。无法设置主键属性&#39; id&#39;现有价值&#39; 1314331&#39;。
那么,就像这种情况一样,如何将数据放入RLMRealm并保持每个人对象是唯一一个由primaryKey?
答案 0 :(得分:1)
试试这个
[[RLMRealm defaultRealm] transactionWithBlock:^{
RLMObject *object = [Books mj_objectWithKeyValues:responseObject];
[[RLMRealm defaultRealm] addOrUpdateObject:object];
} error:nil];