didReceiveMemoryWarning

didReceiveMemoryWarning

本文介绍了NSNotificationCenter removeObserver:注销VC是否收到MemoryWarning通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在我的应用程序中发生了一个问题:我测试了 didReceiveMemoryWarning 调用一个 UIViewController ,包括以下内容-up调用 viewDidUnload



这个以前在我的应用程序的旧版本中工作正常,但在iPhone模拟器中现在不起作用:
didReceiveMemoryWarning 不再被调用了。



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

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



设计是否有这种行为?我找不到指向的引用/文档,在UIViewController内调用 removeObserver:会破坏标准的memoryWarning处理。

解决方案

是的,这是设计的。



这个行为根本不让我感到惊讶。 UIViewController的实现是不透明的,所以没有办法知道它正在注册 UIApplicationDidReceiveMemoryWarningNotification didReceiveMemoryWarning



作为一般规则,使用 [[NSNotificationCenter defaultCenter] removeObserver:self]是不好的做法/ code>任何地方,但在 dealloc 。这是因为,如您所见,超类实现中可能会出现不可预知的副作用。如果您遵循仅注册您注册的特定通知的注册约定,则可以更准确地调试/维护您的代码。


I just stumbled about an issue in my app: I tested the didReceiveMemoryWarning calls to an UIViewController including the follow-up calls for viewDidUnload.

This used to work fine in older versions of my app, but was not working now within iPhone Simulator: didReceiveMemoryWarning was just not called any more.

This was caused by calling [NSNotificationCenter defaultCenter] removeObserver:self] in viewWillDisappear (self being the UIViewController) to unregister for some lifecycle notifications I did add in viewDidAppear.

That global removeObserver: call did not only remove my added notifications, but apparently also the system's UIApplicationDidReceiveMemoryWarningNotification notification caused the UIViewController's didReceiveMemoryWarning being called.

Is this behaviour by design? I could not find a reference/document which was pointing out, that calling removeObserver: within a UIViewController breaks the standard memoryWarning handling.

解决方案

Yes, this is by design.

This behavior doesn't surprise me at all. The implementation of UIViewController is opaque so there is no way to know for sure that it is registering instances for UIApplicationDidReceiveMemoryWarningNotification with the didReceiveMemoryWarning action but that would certainly make sense.

As a general rule, it's bad practice to use [[NSNotificationCenter defaultCenter] removeObserver:self] anywhere but in dealloc. This is because, as you've discovered, there can be unpredictable side effects in superclass implementations. It's more predictable and easier to debug/maintain your code if you follow the convention of only unregistering for the specific notifications you registered for.

这篇关于NSNotificationCenter removeObserver:注销VC是否收到MemoryWarning通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 06:58