简体   繁体   English

Swift中的键值观察4

[英]Key-Value Observing in Swift 4

I have the following code in my Swift 4 project. 我在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()
    }

Whenever the dishes array is changed, the observation is triggered. 每当更换餐具阵列时,都会触发观察。 But my question is how can I get the actual changes that happened, that is, how can I access the actual Dish object that triggered the change? 但我的问题是如何才能获得发生的实际更改,即如何访问触发更改的实际Dish对象?

I think the reason change is coming up with nil is because you haven't specified options. 我认为change的原因是nil因为你没有指定选项。

Rewrite as follows: 重写如下:

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()
}

Note that I have done a bit of guesswork here about your Dish object. 请注意,我在这里做了一些关于Dish对象的猜测。 I am assuming you have made it conform to the Equatable protocol, and this is a necessary step for the solution to work. 我假设你已经使它符合Equatable协议,这是解决方案工作的必要步骤。

UPDATE: This requirement has now been reflected in the official Apple documentation here . 更新:此要求现已反映在此处的官方Apple文档中。

If you don't need to know how a property has changed, omit the options parameter. 如果您不需要知道属性的更改方式,请省略options参数。 Omitting the options parameter forgoes storing the new and old property values, which causes the oldValue and newValue properties to be nil. 省略options参数以放弃存储新旧属性值,这会导致oldValue和newValue属性为nil。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM