在Swift 4中,如何删除基于块的KVO观察器? [英] In Swift 4, how do I remove a block-based KVO observer?

查看:113
本文介绍了在Swift 4中,如何删除基于块的KVO观察器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样存储观察者:

If I store an observer like this:

let observer: NSKeyValueObservation = foo.observe(\.value, options: [.new]) { (foo, change) in
    print(change.newValue)
}

一旦不再需要如何删除/禁用/清理observer?

How do I remove/disable/cleanup observer once I no longer need it?

我的foo实例没有任何接收NSKeyValueObservation实例的类似remove的方法,observer本身也没有任何类似remove的方法.

My foo instance does not have any remove-like method that receives an NSKeyValueObservation instance, the observer itself doesn't have any remove-like either.

推荐答案

在iOS 11中,您不必这样做.只是让观察者超出范围即可.让观察者在观察者之前死亡或在观察者之前使观察者死亡不再有任何惩罚,因此您没有实际工作要做.

In iOS 11, you don't have to. Just let the observer go out of scope. There is no penalty any longer for letting an observer die before the observed or for letting the observed die before the observer, so you have no actual work to do.

另一方面,如果您确实要注销注册观察者,则将其从保留它的任何东西中删除,或告诉它invalidate. (必须保留一些东西,因为如果您不坚持观察者,那么它会死掉,并且永远不会调用您的观察者函数.)

On the other hand, if you really want to unregister the observer, remove it from whatever is retaining it, or tell it to invalidate. (Something must be retaining it, because if you don't persist the observer, it will die and your observer function will never be called.)

(您说如果我像这样存储观察者",但是使用let进行存储的方式有点不明智,可以存储观察者.最好将其放入Set中您可以稍后将其删除,或至少将其存储在可选的var中,然后将其设置为nil.)

(You say "if I store an observer like this", but the way you are storing it, with let, is a somewhat silly way to store the observer. It would be better to put it in a Set from which you can remove it later, or at least store it in a Optional var that you can later set to nil.)

这篇关于在Swift 4中,如何删除基于块的KVO观察器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆