反向链接领域
Backlinking Realm
嗨,我正在玩 Realm,我正在尝试获取和输出:
Fido has 1 owners (["John"])
Rex has 2 owners (["Mary","Bob"])
虽然我不断得到这个输出:
Fido has 1 owners (["John"])
Rex has 1 owners (["Mary"])
Rex has 1 owners (["Bob"])
这是我使用的代码:
// this in the app delegate
try! realm.write {
realm.create(Person.self, value: ["John", [["Fido", 1]]])
realm.create(Person.self, value: ["Mary", [["Rex", 2]]])
realm.create(Person.self, value: ["Bob", [["Rex", 2]]])
}
// Log all dogs and their owners using the "owners" inverse relationship
let allDogs = realm.objects(Dog)
for dog in allDogs {
let ownerNames = dog.owners.map { [=12=].name }
print("\(dog.name) has \(ownerNames.count) owners (\(ownerNames))")
}
class Dog: Object {
dynamic var name = ""
dynamic var age = 0
var owners: [Person] {
// Realm doesn't persist this property because it only has a getter defined
// Define "owners" as the inverse relationship to Person.dogs
return linkingObjects(Person.self, forProperty: "dogs")
}
}
class Person: Object {
dynamic var name = ""
let dogs = List<Dog>()
}
如有帮助,谢谢。
从外观上看,您正在创建一个完全独立的 Rex
副本,每次您向数据库添加一个新的所有者,而不是重复使用同一个。
最好事先单独创建 Dog
个对象,然后在创建 Person
个对象时直接引用这些对象。
嗨,我正在玩 Realm,我正在尝试获取和输出:
Fido has 1 owners (["John"])
Rex has 2 owners (["Mary","Bob"])
虽然我不断得到这个输出:
Fido has 1 owners (["John"])
Rex has 1 owners (["Mary"])
Rex has 1 owners (["Bob"])
这是我使用的代码:
// this in the app delegate
try! realm.write {
realm.create(Person.self, value: ["John", [["Fido", 1]]])
realm.create(Person.self, value: ["Mary", [["Rex", 2]]])
realm.create(Person.self, value: ["Bob", [["Rex", 2]]])
}
// Log all dogs and their owners using the "owners" inverse relationship
let allDogs = realm.objects(Dog)
for dog in allDogs {
let ownerNames = dog.owners.map { [=12=].name }
print("\(dog.name) has \(ownerNames.count) owners (\(ownerNames))")
}
class Dog: Object {
dynamic var name = ""
dynamic var age = 0
var owners: [Person] {
// Realm doesn't persist this property because it only has a getter defined
// Define "owners" as the inverse relationship to Person.dogs
return linkingObjects(Person.self, forProperty: "dogs")
}
}
class Person: Object {
dynamic var name = ""
let dogs = List<Dog>()
}
如有帮助,谢谢。
从外观上看,您正在创建一个完全独立的 Rex
副本,每次您向数据库添加一个新的所有者,而不是重复使用同一个。
最好事先单独创建 Dog
个对象,然后在创建 Person
个对象时直接引用这些对象。