gpt4 book ai didi

ios - NSNotificationCenter 是否 removeObserver : deregister a VC from receiving MemoryWarning Notifications?

转载 作者:技术小花猫 更新时间:2023-10-29 10:33:48 28 4
gpt4 key购买 nike

我刚刚在我的应用程序中偶然发现了一个问题:我测试了 didReceiveMemoryWarning调用 UIViewController包括后续电话 viewDidUnload .

这曾经在我的应用程序的旧版本中运行良好,但现在在 iPhone 模拟器中无法运行: didReceiveMemoryWarning只是不再被调用了。

这是调用 [NSNotificationCenter defaultCenter] removeObserver:self] 引起的在 viewWillDisappear (自己是 UIViewController)取消注册我在 viewDidAppear 中添加的一些生命周期通知.

那个全局removeObserver:调用不仅删除了我添加的通知,而且显然系统的 UIApplicationDidReceiveMemoryWarningNotification 通知也导致了 UIViewController 的 didReceiveMemoryWarning被调用。

这是设计使然的行为吗?我找不到指出的引用/文档,调用 removeObserver:在 UIViewController 中打破了标准的 memoryWarning 处理。

最佳答案

是的,这是设计使然。

这种行为一点也不让我吃惊。 UIViewController 的实现是不透明的,因此无法确定它是否正在使用 didReceiveMemoryWarning 操作为 UIApplicationDidReceiveMemoryWarningNotification 注册实例,但这肯定是有道理的。

作为一般规则,在 dealloc 之外的任何地方使用 [[NSNotificationCenter defaultCenter] removeObserver:self] 都是不好的做法。这是因为,正如您所发现的,父类(super class)实现中可能存在不可预测的副作用。如果您遵循仅取消注册您注册的特定通知的惯例,那么调试/维护您的代码会更容易预测和更容易。

关于ios - NSNotificationCenter 是否 removeObserver : deregister a VC from receiving MemoryWarning Notifications?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5627001/

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