核心数据+iCloud如何处理云数据更新



我试图弄清楚如何处理来自云的数据更新。在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];
}

据我所知,关键是对代码进行以下更改:AppDelegate:

...
NSPersistentStoreDescription *description = [_persistentContainer.persistentStoreDescriptions firstObject];
[description setOption:@(true) forKey:NSPersistentStoreRemoteChangeNotificationPostOptionKey];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
...

控制器:

...
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(remoteHandler:)
name:NSPersistentStoreRemoteChangeNotification
object:nil];
...

现在UI正在更新,但看起来只有在应用程序转到后台并返回活动状态之后。

最新更新