【问题标题】:iOS UIApplicationWillEnterForegroundNotification Without Memory Leak?iOS UIApplication WillEnterForegroundNotification 没有内存泄漏?
【发布时间】:2018-01-30 16:30:23
【问题描述】:

我目前在我的 Objective-C 应用程序中使用这种方法:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleEnteredForeground) name:UIApplicationWillEnterForegroundNotification object:nil];

如果我不删除它

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil]; 

我是否有内存泄漏的风险?或者有没有一种很好的方法来利用这个通知而不会有内存泄漏的风险?

【问题讨论】:

  • NSNotificationCenter 不保留其观察者,所以不,您没有内存泄漏的风险。
  • 字!随意折腾一个答案,我会接受它!
  • @TomHammond 但不仅如此。存在悬空指针的危险(iOS 9 之前的版本)。

标签: ios objective-c memory-leaks


【解决方案1】:

没有内存泄漏的危险;通知中心对您的观察者self 的引用很弱。

但是存在一个危险——即self 将不复存在,通知中心稍后将尝试向其发送通知。这将导致可怕的崩溃,非常难以追踪(悬空指针)。

这就是为什么您必须确保在 iOS 8 及之前的版本中取消注册您的观察者。

然而,从 iOS 9 开始,这不再是一个问题,因为通知中心对观察者的引用不是简单地弱,而是 ARC 弱。这意味着对已释放观察者的引用变为nil。通知中心检测到这一点并安全地停止向其发送通知。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-30
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
相关资源
最近更新 更多