在 NSNotificationCenter 中添加/删除观察者的最佳实践
在 NSNotificationCenter
中添加和删除观察者的最佳实践是什么?
我想知道是否在 viewDidLoad 中添加
并在 self
作为观察者viewDidUnload
中删除 self
就足够了。或者也许我也应该删除 dealloc
中的 self
。
也许需要考虑内存不足的情况。我可以看到在 viewDidLoad
中添加并在 dealloc
中删除存在问题:由于内存不足而调用 viewDidUnload
...然后 viewDidLoad<当视图再次显示时 /code> 被调用...现在
self
已被添加为观察者两次而没有被删除(因为 dealloc
未被调用) 。
注意:我正在考虑一个基本示例,其中 self
引用 UIViewController
子类。
What's the best practice for adding and removing observers to/from NSNotificationCenter
?
I'm wondering if adding self
as an observer in viewDidLoad
and removing self
in viewDidUnload
is sufficient. Or perhaps I should remove self
in dealloc
as well.
Perhaps low memory conditions need to be considered. I could see adding in viewDidLoad
and removing in dealloc
being problematic: viewDidUnload
is called due to low memory... then viewDidLoad
is called when the view is displayed again... now self
has been added as an observer twice w/o being removed (since dealloc
wasn't called).
Note: I'm considering just a basic example where self
refers to a UIViewController
subclass.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常在
viewWillAppear
中注册我的UIViewController
观察者,并在viewWillDisappear
中删除。对我来说,
viewWillDisappear
似乎比viewWillUnload
更安全,因为后一个方法仅在低于 5.0 的 iOS 版本低内存的情况下才会被调用。最合适的答案可能取决于您的视图控制器正在做什么。您是否期望在视图显示之前收到(并需要做出反应)通知?如果是这样,也许在 viewDidLoad 中添加观察者对您来说是正确的选择。
I usually do my
UIViewController
observer registering inviewWillAppear
and my removing inviewWillDisappear
.viewWillDisappear
seems like a safer choice to me thanviewWillUnload
since the latter method only gets called in low-memory situations on iOS versions older than 5.0.The most appropriate answer probably depends on what your view controller is doing. Do you expect to get (and need to react to) notifications before your view even gets displayed? If so, maybe adding the observer in
viewDidLoad
is the right thing for you.对于 iOS 9+ 和 OS X 10.11+,WWDC 2015 第 202 场会议“Cocoa 的新功能” 宣布:
NSNotificationCenter
解除分配的观察者会自动取消注册,
无需调用,请参阅
:视频 33:27,pdf 幻灯片 241
For iOS 9+ and OS X 10.11+, the WWDC 2015 session 202 "What's New in Cocoa" announced:
NSNotificationCenter
Deallocated observers are automatically unregistered
No need to call
see: video at 33:27, pdf slide 241