NSNotificationCenter管理

来源:互联网 发布:asp编程培训 编辑:程序博客网 时间:2024/06/05 11:18

最近做项目遇到一个问题,本来以为是segue的问题,查了一下发现是NSNotificationCenter的问题

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Could not find a navigation controller for segue 'mapToBusLineVC'. Push segues can only be used when the source controller is managed by an instance of UINavigationController.'


当某个notification被post之后,观察者的方法被多次调用。于是想到,难道是多次添加了观察者,而没有删除?于是看了下苹果官方文档中的代码,发现官方例子中是在viewWillAppear的时候添加,viewWillDisappear的时候remove。

现在我们来深入思考下为什么不能在dealloc中调用[[NSNotificationCenter defaultCenter] removeObserver:self]。首先,让我们来想在添加观察者的时候,我们观察者的retainCount被+1了吗?如果没有被+1,那么当这个类会在retainCount为0时被销毁,通知中心就无法通知到该类,那么remove方法还有意义吗?所以在添加观察者的时候,通知中心必然会将该观察者的retainCount+1,既然通知中心retain了这个观察者,那么很不幸,这个观察者的dealloc方法永远不会被调用,他的retainCount最少也是1,因为通知中心retain了一次,结果[[NSNotificationCenter defaultCenter] removeObserver:self];就永远不被调用。

  所以正确的做法是按照官方例子中的方法来做。


0 0
原创粉丝点击