更新 Core Data 对象时更新 UIViewController

Update UIViewController when Core Data objects are updated

我想绑定数据源和视图控制器

我用的是Core Data,dataSource是NSManagedObject的一个集合,当收到web socket通知时,我更新了Core Data中的数据,如何让view controller更新UI自动。

一个选项是使用 NSFetchResultsController,如果您的控制器看起来像一个项目列表。 另一种选择是监听网络套接字通知,并在得到答案时重新加载 UI。

如果您使用 UITableView,则可以使用 NSFetchedResultsController。 否则,您可以使用 NSNotificationCenter。演示使用:

在你的ViewController,

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUI:) name:@"updateUI" object:nil];

Post更新数据后的通知

 [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUI" object:nil];

然后在方法 updateUI 中,您可以进行 UI 更新。