加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift中的键值观察4

发布时间:2020-12-14 04:43:14 所属栏目:百科 来源:网络整理
导读:我在 Swift 4项目中有以下代码. class DishesTableViewController : UITableViewController { private var token :NSKeyValueObservation? @objc dynamic private(set) var dishes :[Dish] = [] override func viewDidLoad() { super.viewDidLoad() // confi
我在 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对象?

解决方法

我认为改变的原因是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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读