gpt4 book ai didi

没有内存泄漏的 iOS UIApplicationWillEnterForegroundNotification?

转载 作者:行者123 更新时间:2023-11-29 00:04:26 33 4
gpt4 key购买 nike

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

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

如果我不使用

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

我有内存泄漏的风险吗?或者有没有一种好方法可以利用此通知而不会有内存泄漏的风险?

最佳答案

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

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

这就是为什么您必须确保在 iOS 8 及更早版本中注销您的观察者。

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

关于没有内存泄漏的 iOS UIApplicationWillEnterForegroundNotification?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48526232/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com