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.
以上是内存溢出为你收集整理的Swift中的键值观察4全部内容,希望文章能够帮你解决Swift中的键值观察4所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)