为什么“领域集"对象随机工作? [英] Why does the Realm Set object work at random?
问题描述
使用Realm对象的set
的函数始终是随机的.
The function to use a set
of Realm objects is always random.
主键不得更改,并且必须唯一.
因此,我添加了另一个变量进行比较.
而且我重写了isEqual(:)函数.
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?
推荐答案
为使Set
正常工作,您的对象需要具有Hashable
的正确实现.领域Object
已经实现了Hashable
,并且可能是==
实现调用了isEqual
.
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
.
但是,hash
也应该与isEqual
保持一致,但是您尚未覆盖hash
.您应实现hash
,以使两个相等的对象(由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.
一种方法是这样做:
override var hash: Int {
return id.hash
}
这篇关于为什么“领域集"对象随机工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!