嗨,我正在玩 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>()
}
如果你能帮忙,谢谢。