如何安全删除观察者(Swift)
我添加了一个观察者
override func viewDidLoad()
{
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector:"selector name", name: "observer name", object:nil)
...
}
在deinit中删除观察者时,
When removing observer in deinit,
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self, forKeyPath: <some string>)
}
该应用有时会崩溃:
由于未捕获的异常"NSRangeException"而终止应用程序,原因:'无法删除观察者类"用于来自的关键路径一些字符串"NSNotificationCenter,因为它没有注册为观察者.
Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer "class" for the key path "some string" from NSNotificationCenter because it is not registered as an observer.
所以我试图添加do/catch
So I am trying to add do/catch
deinit
{
do{
try NSNotificationCenter.defaultCenter().removeObserver(self, forKeyPath: <some string>)
}catch{}
}
但是我得到警告:
catch块无法访问,因为do块中没有抛出任何错误
catch block is unreachable because no errors are thrown in do block
应用程序崩溃
当我添加尝试时
deinit
{
do{
try NSNotificationCenter.defaultCenter().removeObserver(self, forKeyPath: <some string>)
}catch{}
}
我收到此警告:
在尝试表达内不会发生对throw函数的调用
no calls to throwing functions occur within try expresion
应用程序崩溃
那应该怎么做?
我认为您应该使用代码
NSNotificationCenter.defaultCenter().removeObserver(self)
说明:您在这里有误:您正在使用NSNotification&NSNotificationCenter,因此您必须使用上面的这段代码删除观察.您已经使用KVO的代码删除了观察者,所以会出错.
Explain: You have mistake here: You are using NSNotification & NSNotificationCenter so you have to using this code above to remove observe. you have use code for KVO to remove observer so it will wrong.
您可以在此处阅读更多详细信息.键-值-观察
More detail you can read at here. Key-Value-Observing