【发布时间】:2020-12-29 15:25:41
【问题描述】:
我试图弄清楚如何处理来自云端的数据更新。 在 Swift 示例应用程序中,所有工作都“从盒子里”开始,但在 Obj-C 中,当应用程序从 iCloud 获取更新的数据时,我无法更新界面。 下面是我用于实例化容器和上下文的代码:
@synthesize persistentContainer = _persistentContainer;
- (NSPersistentCloudKitContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
if (_persistentContainer == nil) {
_persistentContainer = [[NSPersistentCloudKitContainer alloc] initWithName:@"SampleCloudObjC"];
NSPersistentStoreDescription *description = [_persistentContainer.persistentStoreDescriptions firstObject];
[description setOption:@(true) forKey:NSPersistentStoreRemoteChangeNotificationPostOptionKey];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}];
}
}
return _persistentContainer;
}
- (void)saveContext {
NSManagedObjectContext *context = self.persistentContainer.viewContext;
context.automaticallyMergesChangesFromParent = YES;
NSError *error = nil;
if ([context hasChanges] && ![context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}
在这里我尝试处理通知:
- (void)viewDidLoad {
[super viewDidLoad];
taskList = [Task fetchAll];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(updateTable)
name:NSPersistentStoreRemoteChangeNotificationPostOptionKey
object:nil];
}
- (IBAction)updateTable {
taskList = [Task fetchAll];
[self.tableView reloadData];
}
【问题讨论】:
-
我认为你需要
NSPersistentStoreRemoteChangeNotification,而不是NSPersistentStoreRemoteChangeNotificationPostOptionKey。 -
我试过了,但不幸的是,它没有帮助。
-
你能解释一下究竟是什么不起作用吗?例如,
updateTable是否被调用?你在你的项目中enable CloudKit and Push Notifications 了吗? -
是的,在项目设置中启用了推送通知。在后台模式下还启用了远程通知。例如,我为表视图调用重新加载数据。我在视图上放了一个按钮,如果我点击它,表格会显示更新的数据,但是当从 iCloud 更新核心数据时,我不知道如何更新 UI。
标签: objective-c core-data icloud