gpt4 book ai didi

ios - 如何安全地移除观察者 (Swift)

转载 作者:IT王子 更新时间:2023-10-29 05:27:10 26 4
gpt4 key购买 nike

我添加了观察者

override func viewDidLoad()
{
super.viewDidLoad()

NSNotificationCenter.defaultCenter().addObserver(self, selector:"selector name", name: "observer name", object:nil)
...
}

在 deinit 中移除观察者时,

deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self, forKeyPath: <some string>)
}

应用有时会崩溃:

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

deinit
{
do{
try NSNotificationCenter.defaultCenter().removeObserver(self, forKeyPath: <some string>)
}catch{}
}

但是我得到一个警告:

catch block is unreachable because no errors are thrown in do block

应用崩溃


当我添加尝试时

deinit
{
do{
try NSNotificationCenter.defaultCenter().removeObserver(self, forKeyPath: <some string>)
}catch{}
}

我收到这个警告:

no calls to throwing functions occur within try expresion

应用崩溃

应该怎么做?

最佳答案

如果您支持 iOS 9.0 版本,则无需在 deinit 方法中自行删除观察者。

摘自文档

In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated.

https://useyourloaf.com/blog/unregistering-nsnotificationcenter-observers-in-ios-9/

关于ios - 如何安全地移除观察者 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33809125/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com