我从服务器获取数据列表。它们是一堆书。我有书、书、人的 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 对象。然后将其添加到 Realm 。
[[RLMRealm defaultRealm] transactionWithBlock:^{
[[RLMRealm defaultRealm] addObject:[Books mj_objectWithKeyValues:responseObject]];
} error:nil];
它崩溃了。因为有两本书有相同的译者。无法将主键属性“id”设置为现有值“1314331”。
那么,像这种情况,如何把数据放到RLMRealm中,并通过primaryKey保证每个person对象是唯一的呢?
最佳答案
试试这个
[[RLMRealm defaultRealm] transactionWithBlock:^{
RLMObject *object = [Books mj_objectWithKeyValues:responseObject];
[[RLMRealm defaultRealm] addOrUpdateObject:object];
} error:nil];
关于ios - Realm Objective-C 写入数据库时如何忽略已经存在的相同主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42944659/