我在
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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。