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];就永远不被调用。
所以正确的做法是按照官方例子中的方法来做。
- NSNotificationCenter管理
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSnotificationcenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSNotificationCenter
- NSnotificationcenter
- NSNotificationCenter
- NSNotificationCenter
- 垃圾回收算法
- 黑马程序员---Java集合的使用
- JS页面截图技术
- 400+考研 北京航空航天大学7系机械工程及自动化学院971机械工程综合资料合辑
- oracle和sql server中回车符和换行符的sql代码
- NSNotificationCenter管理
- 第二章 Spring MVC入门 —— 跟开涛学SpringMVC
- 黑马程序员——java基础之String
- Tweenjs中的MotionGuidePlugin示例
- iOS面试题集锦
- Oracle 动态 SQL
- C语言static
- C#趣味程序---爱因斯坦的台阶问题
- string和stringstream用法总结