代码之家  ›  专栏  ›  技术社区  ›  Alk

散列==方法不检测两个对象swift之间的差异

  •  0
  • Alk  · 技术社区  · 5 年前

    我实施了以下课程:

        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

    我的目标是刷新 UICollectionView 随着对 tables 数组,但是框架没有检测到任何更改,即使 == timeRemaining currentPrice

    1 回复  |  直到 5 年前
        1
  •  1
  •   Bill    5 年前

    让newItems=旧项

    因为两个数组都包含对象实例,它们不就指向相同的对象吗?所以当你迭代 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
            }
        }
    }