gpt4 book ai didi

ios - Hashable == 方法无法快速检测两个对象之间的差异

转载 作者:行者123 更新时间:2023-11-28 05:45:47 28 4
gpt4 key购买 nike

我实现了下面的类:

    class Table : Hashable {

var uid : Int
var timeRemaining : Int?
var currentPrice : Double?
var hashValue: Int {
return uid.hashValue
}

static func ==(lhs: Table, rhs: Table) -> Bool {
return lhs.uid == rhs.uid && lhs.timeRemaining == rhs.timeRemaining && lhs.currentPrice == rhs.currentPrice
}

init (uid: Int, timeRemaining: Int?, currentPrice: Double?) {
self.uid = uid
self.timeRemaining = timeRemaining
self.currentPrice = currentPrice
}
}

我还定义了这个类的对象数组:

private var tables = [Table]()

接下来,我有以下每秒运行一次的方法:

func updateAuctions() {
let oldItems = tables
let newItems = oldItems
for table in newItems {
let oldPrice = table.currentPrice!
let timeRemaining = table.timeRemaining!
table.currentPrice = oldPrice + 0.50
table.timeRemaining = timeRemaining - 1
}
let changes = diff(old: oldItems, new: newItems)

collectionView.reload(changes: changes, section: 0) { (complete) in
if (complete) {
self.tables = newItems
}
}
}

这使用此处描述的 DeepDiff 框架:https://github.com/onmyway133/DeepDiff

我的目标是使用对 tables 数组所做的更改来刷新 UICollectionView,但是框架没有检测到任何更改,即使我的 == 方法检查 timeRemainingcurrentPrice 是否匹配。

最佳答案

let newItems = oldItems

既然两个数组都包含对象实例,那么它们不就指向相同的对象吗?因此,当您遍历 newItems 并更改值时,您实际上也在更改 oldItems 的值。您可以通过在 for 循环之后打印两个数组的值来验证这一点。

也许你可以试试类似下面的东西?

func updateAuctions() {
let oldItems = tables
let newItems = [Table]()
for item in oldItems {
newItems.append(Table(uid: item.uid, timeRemaining: item.timeRemaining! - 1, currentPrice: item.currentPrice! + 0.50))
}
let changes = diff(old: oldItems, new: newItems)

collectionView.reload(changes: changes, section: 0) { (complete) in
if (complete) {
self.tables = newItems
}
}
}

关于ios - Hashable == 方法无法快速检测两个对象之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54836754/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com