I have a class that synchronizes data in the background every once in a while. The user can be anywhere in the app’s navigation tree and no matter where the user is I need to be able to update the view controllers with whatever new data I just synchronized.
I put the object in charge of the background thread sync as a property of the SharedAppDelegate.
In a way I need to implement something like the Observer pattern and every time I instantiate a view controller set it to listen to some event on the background sync object so that after every sync I can execute a method in the view controllers that are listening.
I’m not sure what the correct way to do this in Objective-C is or if there is even a better or recommended way.
Use a
NSNotificationwithNSNotificationCenter, which fits precisely your purpose :in your AppDelegate, when the sync ends, call
in every view controller you display, call
also do not forget to remove the observer when it’s not needed anymore (view controller deallocated / unloaded / not visible, up to you ), or the
NSNotificationCenterwill end up crashing :A few notes :
This example uses the block-based API to perform the UI refresh work on the main operation queue (implying on the main thread), because you must not perform UIKit operations on any other thread than the main thread. This is likely that your background sync will send its notification on an other thread, so switching to the main thread is necessary. If you want to use the selector-based API, be sure to send the notification on the main thread.
You can register as many observers on the notification as you want, so this matches perfectly your pattern (
NSNotificationsare usually the best way to notify different app components of an app-wide event like sync end).The
objectparameter passed when posting the notification allows you to access the sync object in the observer block usingnote.objectif you need it.