将某个事件通知所有已加载的 ViewController [英] Notify all loaded ViewControllers of a certain event
问题描述
我有一个类,每隔一段时间就会在后台同步数据.用户可以位于应用导航树中的任何位置,无论用户在哪里,我都需要能够使用我刚刚同步的任何新数据更新视图控制器.
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.
我把负责后台线程同步的对象作为 SharedAppDelegate 的一个属性.
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.
我不确定在 Objective-C 中执行此操作的正确方法是什么,或者是否有更好或推荐的方法.
推荐答案
使用 NSNotification
和 NSNotificationCenter
,正好符合您的目的:
Use a NSNotification
with NSNotificationCenter
, which fits precisely your purpose :
在你的 AppDelegate 中,当同步结束时,调用
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... }
也不要忘记在不再需要时移除观察者(视图控制器释放/卸载/不可见,由您决定),否则 NSNotificationCenter
最终会崩溃:
[[NSNotificationCenter defaultCenter] removeObserver:_myObserver];
一些注意事项:
此示例使用基于块的 API 在主操作队列上执行 UI 刷新工作(暗示在主线程上),因为您不得在主线程之外的任何其他线程上执行 UIKit 操作.这很可能是您的后台同步将在另一个线程上发送它的通知,因此切换到主线程是必要的.如果要使用基于选择器的 API,请务必在主线程上发送通知.
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.
您可以根据需要在通知上注册任意数量的观察者,因此这与您的模式完美匹配(NSNotifications
通常是通知不同应用程序组件的应用程序范围事件(如同步结束)的最佳方式).
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).
发布通知时传递的 object
参数允许您在需要时使用 note.object
访问观察者块中的同步对象.
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.
这篇关于将某个事件通知所有已加载的 ViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!