Notify all loaded ViewControllers of a certain event

点点圈 提交于 2019-12-24 00:58:00

问题


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.


回答1:


Use a NSNotification with NSNotificationCenter, which fits precisely your purpose :

  • in your AppDelegate, when the sync ends, call

    [[NSNotificationCenter defaultCenter] postNotificationName:@"SyncEnded" object:mySyncObject]
    
  • in every view controller you display, call

    _myObserver = [[NSNotificationCenter defaultCenter] addObserverForName:@"SyncEnded" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){ ...your UI refresh code... }
    
  • 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 NSNotificationCenter will end up crashing :

    [[NSNotificationCenter defaultCenter] removeObserver:_myObserver];
    

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 (NSNotifications are usually the best way to notify different app components of an app-wide event like sync end).

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



来源:https://stackoverflow.com/questions/11878265/notify-all-loaded-viewcontrollers-of-a-certain-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!