嗨,我正在玩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 { $0.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>()
}
感谢您的帮助。
答案 0 :(得分:1)
从它的外观来看,每次向数据库添加新所有者时,都会创建一个完全独立的Rex
副本,而不是重新使用相同的副本。
最好分别创建Dog
对象,然后在创建Person
对象时直接引用这些对象。