Why does the Realm Set object work at random?

2019-08-28 05:59发布

The function to use a set of Realm objects is always random.

Primary keys must not be changed and they must be unique.
So I added another variable for compare.
And I override isEqual(:) function.

See below my code.

class Model: Object {
    @objc dynamic var key = ""
    @objc dynamic var id = ""

    override static func primaryKey() -> String? {
        return "key"
    }

    override func isEqual(_ object: Any?) -> Bool {
        if let object = object as? Model {
            return id == object.id
        } else {
            return false
        }
    }
}

let model1 = Model()
model1.key = UUID().uuidString
model1.id = "hi"

let model2 = Model()
model2.key = UUID().uuidString
model2.id = "hi"

let model1Array = [model1]
let model2Array = [model2]

let set1 = Set(model1Array)
let set2 = Set(model2Array)
let result = set1.intersection(set2)
print(result) // []
let result = set1.intersection(set2)
print(result) // [Model { key = 9E814B97-D0CC-4550-BF7B-19645C1DB746; id = hi; }]
let result = set1.intersection(set2)
print(result) // []
let result = set1.intersection(set2)
print(result) // []
let result = set1.intersection(set2)
print(result) // [Model { key = 8A399388-1FA2-4699-8258-5DA5DFCEC203; id = hi; }]

Every time I run, the values come out randomly.
What did I do wrong?

标签: ios swift realm
1条回答
来,给爷笑一个
2楼-- · 2019-08-28 06:28

For Set to work correctly, your objects need to have a correct implementation of Hashable. The Realm Object already implements Hashable, and presumably, the == implementation calls isEqual.

However, the hash should be consistent with isEqual as well, but you haven't overridden hash yet. You should implement hash such that two equal objects (as determined by isEqual) have equal hashes.

One way is to do it like this:

override var hash: Int {
    return id.hash
}
查看更多
登录 后发表回答