2

嗨,我正在玩 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>()
}

如果你能帮忙,谢谢。

4

1 回答 1

1

从外观上看,您正在创建一个完全独立的Rex副本,每次您向数据库添加新所有者时,而不是重复使用同一个所有者。

最好Dog提前单独创建对象,然后在创建对象时直接引用这些Person对象。

于 2015-12-23T03:24:59.223 回答