Reputation: 3463
Hi I'm playing around with Realm and I'm trying to get and output of:
Fido has 1 owners (["John"])
Rex has 2 owners (["Mary","Bob"])
Though I keep on getting this output:
Fido has 1 owners (["John"])
Rex has 1 owners (["Mary"])
Rex has 1 owners (["Bob"])
Here is the code I'm using:
// 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>()
}
Thank you if you can help.
Upvotes: 2
Views: 144
Reputation: 16021
From the look of it, you're creating a completely separate Rex
copy, each time you're adding a new owner to the database, not re-using the same one.
It might be better to create the Dog
objects separately, in advance, and then reference those objects directly when creating the Person
objects.
Upvotes: 1