Why does the Realm Set object work at random?

∥☆過路亽.° 提交于 2019-12-13 03:04:01

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/56232273/why-does-the-realm-set-object-work-at-random

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!