【问题标题】:Hashable == method does not detect difference between two objects swiftHashable == 方法不能快速检测两个对象之间的差异
【发布时间】:2019-02-22 23:50:03
【问题描述】:

我实现了下面的类:

    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 匹配.

【问题讨论】:

    标签: ios swift uicollectionview hashable equatable


    【解决方案1】:

    让 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
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-02
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      相关资源
      最近更新 更多