Search code examples
ios6nsnotificationsdidreceivememorywarningviewdidunload

NSNotification & didReceiveMemoryWarning in iOS 6


As of iOS 6.0 , viewDidUnload method is deprecated. Before iOS 6 I used to removeObserver of NSNotification in viewDidUnload method. But since it is deprecated , I have moved it to didReceiveMemoryWarning. Now if my app receives the low memory waring , notification are removed. So my code written in NSNotification doesn't work.

Can anybody tell me how can I solve this issue ?

Thanks in advance.


Solution

  • I assume that you added the observer in viewDidLoad. The problem is that on iOS 6 views are not unloaded, even in a low memory situation. Therefore, if you remove the observer in didReceiveMemoryWarning, viewDidLoad will not be called again.

    There are two relative simple alternatives that you can choose from:

    • Add the observer in viewWillAppear and remove it in viewWillDisappear.
    • Add the observer in your initXXX method and remove it in dealloc.

    I is possible to add the observer in viewDidLoad and remove it in didReceiveMemoryWarning. But then you have to "manually unload" the view in didReceiveMemoryWarning, so that viewDidLoad is later called again. See e.g. https://stackoverflow.com/a/15805715/1187415 for sample code how to forcibly unload the view.