我有一个对象有很多狗的人。 App有单独的页面,它显示只是狗和其他的页面,它显示了人的狗领域 - 无法用现有的主键值创建对象
我的模型如下
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"
}
}
我存储在境界的人。人有详细信息页面,我们可以获取并展示他的狗。如果狗已经存在,我更新该狗的最新信息并将其添加到人的狗列表中,否则创建新狗,保存并将其添加到人员列表中。这在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)
}
}
在试图与他的狗,更新的人,境界抛出异常 不能与现有的主键值创建对象
凡在'person.dogs.append(配方)的'recipe'值'是从哪里来的?这是不是很清楚你想在这里做什么,对不起! – TiM
对不起,它一定是person.dogs.append(狗)。我只是创建/更新狗,并将其添加到人的狗@TiM –
啊好吧。我想我现在看到这里发生了什么。我会添加一个答案。 :) – TiM