Swift 4 中的键值观察

Key-Value Observing in Swift 4

我的 Swift 4 项目中有以下代码。

class DishesTableViewController : UITableViewController {


    private var token :NSKeyValueObservation?

    @objc dynamic private(set) var dishes :[Dish] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        // configure the observation
        token = self.observe(\.dishes) { object, change in

            // change is always nil
            print(object)
            print(change)
        }

        updateTableView()
    }

每当菜肴数组发生变化时,就会触发观察。但我的问题是如何获得实际发生的变化,即如何访问触发变化的实际 Dish 对象?

我认为 change 提出 nil 的原因是因为您没有指定选项。

改写如下:

override func viewDidLoad() {
    super.viewDidLoad()

    // configure the observation
    token = self.observe(\.dishes, options: [.new,.old]) { object, change in

        print(object)
        let set1 = Set(change.newArray!)
        let set2 = Set(change.oldArray!)

        let filter = Array(set1.subtract(set2))
        print(filter)

    }

    updateTableView()
}

请注意,我在这里对您的 Dish 对象做了一些猜测。我假设您已使其符合 Equatable 协议,这是解决方案工作的必要步骤。

更新:此要求现已反映在 Apple 官方文档中 here

If you don't need to know how a property has changed, omit the options parameter. Omitting the options parameter forgoes storing the new and old property values, which causes the oldValue and newValue properties to be nil.