Notify all loaded ViewControllers of a specific event

I have a class that from time to time synchronizes data in the background. The user can be anywhere in the application navigation tree, and no matter where the user is, I need to be able to update the view controllers with any new data that I just synchronized.

I set the object responsible for synchronizing the background thread as the SharedAppDelegate property.

In a sense, I need to implement something like the Observer pattern, and every time I create an instance of the view controller, it must listen for some event against the background of synchronization, so after each synchronization I can execute the method in the view controllers, they listen.

I'm not sure if the correct way to do this is in Objective-C, or if there is even a better or recommended way.

+2
source share
1 answer

Use NSNotification with an NSNotificationCenter that matches your purpose:

  • in the AppDelegate application, when the synchronization ends, call

     [[NSNotificationCenter defaultCenter] postNotificationName:@"SyncEnded" object:mySyncObject] 
  • in each displayed view controller, call

     _myObserver = [[NSNotificationCenter defaultCenter] addObserverForName:@"SyncEnded" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){ ...your UI refresh code... } 
  • also do not forget to delete the observer when it is no longer needed (the view controller is freed / unloaded / does not appear, it’s up to you) or the NSNotificationCenter crashes:

     [[NSNotificationCenter defaultCenter] removeObserver:_myObserver]; 

A few notes:

This example uses a block-based API to do the work of updating the user interface in the main operation queue (implied in the main thread), since you should not perform UIKit operations on any other thread except the main thread. Your background synchronization will probably send its notification on another thread, so you need to switch to the main thread. If you want to use the selector-based API, be sure to send a notification to the main thread.

You can register as many observers in the notification as you want, so this fits your template perfectly ( NSNotifications is usually the best way to notify various application components for the entire application, such as the end of synchronization).

The object parameter passed when the notification was sent allows you to access the synchronization object in the observer block using note.object if you need it.

+2
source

Source: https://habr.com/ru/post/1486573/


All Articles