ios - Realm Objective-C 写入数据库时​​如何忽略已经存在的相同主键?

标签 ios objective-c realm

我从服务器获取数据列表。它们是一堆书。我有书、书、人的 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/

相关文章:

swift - Realm 中具有可选 Int 类型的空数据抛出异常

ios - 推送 View Controller 和添加 Controller View 有什么区别?

iphone - 如何在 TableView 中创建带有标签的工具栏?

objective-c - iOS:使用相机时放大到屏幕的一部分

iphone - 有没有办法让 UIScrollView 在任意位置停止和反弹

realm - swift 3.0 : Type 'RLMResults<RLMObjectType>' does not conform to protocol 'Sequence'

ios - 在 iPhone 中使用数组动态创建 tableView 部分

ios - objective-c:分配与综合/保留

iphone - 在 Cocos2d 中更改多个 Sprite 的不透明度

ios - 知道 Realm Collection Change 通知中对象的哪个元素发生了变化?