Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 240
marcus Avatar asked Apr 11 '11 20:04

marcus


2 Answers

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.

like image 139
XJones Avatar answered Sep 28 '22 05:09

XJones


[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.

like image 42
Andrew Veselov Avatar answered Sep 28 '22 07:09

Andrew Veselov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!