Search code examples
iosuiviewcontrollernotificationcenterios-lifecycle

Observing notifications from ViewController


When data is updated in database, I post a notification to NotificationCenter from client with new data. A ViewController will be observing this notification so UI can be updated accordingly.
Will the app crash if view controller observes a new notification and tries to update UI, while its not the present View Controller on screen?
or will the function that observes notification wait until view controller is presented to execute?


Solution

  • If your notifications are only meaningful when your view controller is on-screen then you should listen in viewWillAppear and stop listening in viewWillDisappear.

    The alternative is to listen for notifications in viewDidLoad and stop listening in dealloc (Objective-C) or deinit (Swift). If you do that your view controller will receive the specified notifications the whole time it's alive, regardless of whether it's visible on screen or not.

    If you continue listening to notifications when your view controller is not front-most then you won't crash, but you will probably make updates that aren't visible, possibly making your app less responsive.

    Alternately, you can use the notifications to update your view controller's model (data store) and make the code smart enough to track when the view controller is visible, and only do UI updates when it is visible.

    EDIT:

    Note that if you register for a notification in viewDidLoad, and your app runs in iOS >= 9, you don't need to unregister for the notification in deinit/ dealloc. The OS now handles unregistering an object for notifications when it gets deallocated.