美文网首页
iOS开发 try {} catch {} 巧用

iOS开发 try {} catch {} 巧用

作者: LearningCoding | 来源:发表于2018-04-13 18:33 被阅读73次

最近遇到一个问题,更改 window.rootViewController 时,导致某个页面 dealloc 时,移除观察者,导致 Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer <SubViewController 0x7fc175001d60> for the key path "age" from <Person 0x7fc172da5be0> because it is not registered as an observer 崩溃,大概意思就是不能移除不存在的观察者。
在 viewdidload 里面添加的观察者,为什么会代码不走呢?
window.rootViewController,原来的如果是一个 tabbarViewController,默认是加载第一个页面,如果不切换 tabbar,其他页面 viewDidLoad 是不走的,这就导致了 观察者没有创建了,当切换 rootViewController 时,原来的 tabbarViewController 的子控制器都会 dealloc,导致崩溃。

苹果系统并没有提供判断是否有某个观察者的方法,我们通过 try {} catch {} 来解决,当然也有其他方法

- (void)dealloc {
  @try {
     // 移除观察者
  }
  @catch (NSException *exception) {
     NSLog(@"没有该观察者");
  }
}

相关文章

网友评论

      本文标题:iOS开发 try {} catch {} 巧用

      本文链接:https://www.haomeiwen.com/subject/dokhkftx.html