简体   繁体   中英

Does NSNotificationCenter removeObserver: deregister a VC from receiving MemoryWarning Notifications?

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 defaultCenter] removeObserver:observer] unregisters observer for all notifications for which it had previously registered (including system notifications). You can use removeObserver:name:object: method for unsubscribing from single notification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM