1

我实现了下面的类:

    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,但是框架没有检测到更改,即使我的==方法检查了timeRemainingcurrentPrice匹配。

4

1 回答 1

1

让 newItems = oldItems

由于两个数组都包含对象实例,它们不只是指向相同的对象吗?因此,当您迭代newItems并更改值时,您实际上也在更改 的值oldItemsfor您可以通过在循环后打印两个数组的值来验证这一点。

也许您可以尝试类似以下的方法?

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-02-23T00:21:54.957 回答