mas*_*ers 7 core-data nsnotificationcenter ios cloudkit
我刚刚使用新的 iOS 13 完成了 CoreData+CloudKit 的设置NSPersistentCloudKitContainer。它工作得非常好,因为我可以使用自动生成的 CoreData 类进行属性访问和本地存储,并NSPersistentCloudKitContainer自动同步设备之间的更改。我遇到的问题是收到远程更改的通知。我检查了苹果的文档和这个国家,你告诉NSPersistentCloudKitContainer的NSPersistentStoreDescription您希望它发送通知,然后将其他对象注册为该通知的观察者。我已经这样做了并添加了一个测试方法来显示检测到远程更改的时间。测试方法生成的警报永远不会生成,但是如果我杀死应用程序并重新打开它,更改就会立即出现。所以我相信远程更改正在同步并集成到本地 CoreData 存储中,但通知不起作用。我已将Background Modes权利添加到我的目标并选择了Remote notification模式。代码如下。任何帮助将不胜感激!
设置发送通知的选项:
- (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:@"<redacted>"];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
// ...
}
else {
// ...
[storeDescription setOption:@(YES) forKey:NSPersistentStoreRemoteChangeNotificationPostOptionKey];
// ...
}
}];
}
}
return _persistentContainer;
}
Run Code Online (Sandbox Code Playgroud)
注册接收通知:
- (void)viewDidLoad {
[super viewDidLoad];
// ...
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changes) name:NSPersistentStoreRemoteChangeNotification object:[CoreDataFunctions persistentContainer]];
}
Run Code Online (Sandbox Code Playgroud)
响应变化的测试方法:
- (void)changes {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Changes received" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
}
Run Code Online (Sandbox Code Playgroud)
你观察到的是持久化容器而不是存储协调器,它应该是这样的:
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(persistentStoreRemoteChangeNotification:) name:NSPersistentStoreRemoteChangeNotification object:_persistentContainer.persistentStoreCoordinator];
Run Code Online (Sandbox Code Playgroud)
小智 2
无论您在何处访问 app\xe2\x80\x99s 持久 CloudKit 容器以获取viewContext,您都需要将该automaticallyMergesChangesFromParent属性设置为true。
lazy var managedContext: NSManagedObjectContext = {\n self.storeContainer.viewContext.automaticallyMergesChangesFromParent = true\n return self.storeContainer.viewContext\n}()\nRun Code Online (Sandbox Code Playgroud)\n\n进行这一行更改将启用该应用程序(由NSFetchedResultsController)能够更新 UI 以响应远程数据更改\xe2\x80\xa6
| 归档时间: |
|
| 查看次数: |
1723 次 |
| 最近记录: |