Dee*_*are 14 realm ios swift realm-mobile-platform
我有一个对象有许多狗的人.应用程序有单独的页面,它只显示狗和其他页面显示人的狗
我的模型如下
class Person: Object {
dynamic var id = 0
let dogs= List<Dog>()
override static func primaryKey() -> String? {
return "id"
}
}
class Dog: Object {
dynamic var id = 0
dynamic var name = ""
override static func primaryKey() -> String? {
return "id"
}
}
Run Code Online (Sandbox Code Playgroud)
我有人存储在Realm中.人有详细页面,我们取,并显示他的狗.如果狗已经存在,我会更新该狗的最新信息并将其添加到人的狗列表中,否则创建新狗,保存并将其添加到人员列表中.这适用于coredata.
// Fetch and parse dogs
if let person = realm.objects(Person.self).filter("id =\(personID)").first {
for (_, dict): (String, JSON) in response {
// Create dog using the dict info,my custom init method
if let dog = Dog(dict: dict) {
try! realm.write {
// save it to realm
realm.create(Dog, value:dog, update: true)
// append dog to person
person.dogs.append(dog)
}
}
}
try! realm.write {
// save person
realm.create(Person.self, value: person, update: true)
}
}
Run Code Online (Sandbox Code Playgroud)
在尝试使用他的狗更新人员时,领域抛出异常 无法使用现有主键值创建对象
TiM*_*TiM 32
这里的问题是,即使你正在创建一个全新的Realm Dog对象,你实际上并没有将那个对象保存到数据库中,因此当你调用时append,你正在尝试添加第二个副本.
当您调用时realm.create(Dog, value:dog, update: true),如果数据库中已存在具有该ID的对象,您只需使用dog您创建的实例中的值更新该现有对象,但该dog实例仍然是一个独立的副本; 它不是Dog数据库中的对象.您可以通过检查是否dog.realm等于来确认nil.
因此,当您调用时person.dogs.append(dog),因为dog尚未在数据库中,Realm会尝试创建一个全新的数据库条目,但由于已经有一个具有该ID的狗而失败.
如果要将该dog对象附加到a person,则需要查询Realm以检索dog引用数据库中条目的正确对象.值得庆幸的是,使用主键支持的Realm对象非常简单,因为您可以使用以下Realm.object(ofType:forPrimaryKey:)方法:
if let person = realm.object(ofType: Person.self, forPrimaryKey: "id") {
for (_, dict): (String, JSON) in response {
//Create dog using the dict info,my custom init method
if let dog = Dog(dict: dict)
{
try! realm.write {
//save it to realm
realm.create(Dog, value: dog, update: true)
//get the dog reference from the database
let realmDog = realm.object(ofType: Dog.self, forPrimaryKey: "id")
//append dog to person
person.dogs.append(realmDog)
}
}
}
try! realm.write {
//save person
realm.create(person .self, value: collection, update: true)
}
}
Run Code Online (Sandbox Code Playgroud)
使用add(_:update:)。
try realm.write {
realm.add(objects, update: Realm.UpdatePolicy.modified)
// OR
realm.add(object, update: .modified)
}
Run Code Online (Sandbox Code Playgroud)
Realm.UpdatePolicy 枚举:
error (default)
modified //Overwrite only properties in the existing object which are different from the new values.
all //Overwrite all properties in the existing object with the new values, even if they have not changed
Run Code Online (Sandbox Code Playgroud)
注意:适用于 Realm Swift 3.16.1
| 归档时间: |
|
| 查看次数: |
12288 次 |
| 最近记录: |