Lew*_*s42 5 core-data cloudkit nspersistentcloudkitcontainer
我发现.NSPersistentStoreRemoteChange通知被多次收到,有时多达 10 次。
我认为这没有害处,但最好的情况是它会耗尽处理能力。
\n所以我的问题是:
\n--
\n我有以下代码来设置我的容器。它包含在单例的初始化程序中,我已经确认它被调用一次。
\nguard let modelURL = Bundle(for: type(of: self)).url(forResource: momdName, withExtension:"momd"),\n let mom = NSManagedObjectModel(contentsOf: modelURL)\n else {\n fatalError(" Error loading model from bundle")\n }\n \n let containerURL = folderToStoreDatabaseIn.appendingPathComponent("Model.sqlite")\n \n container = NSPersistentCloudKitContainer(name: momdName, managedObjectModel: mom)\n \n guard let description = container.persistentStoreDescriptions.first else {\n fatalError(" ###\\(#function): Failed to retrieve a persistent store description.")\n }\n \n description.url = containerURL\n description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)\n description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)\n \n super.init()\n \n // this must be called after super.init()\n // ***** ADD OBSERVER *****\n NotificationCenter.default.addObserver(self,\n selector: #selector(updatedFromCKCD(_:)),\n name: .NSPersistentStoreRemoteChange,\n object: container.persistentStoreCoordinator)\n \n if let tokenData = try? Data(contentsOf: tokenFile) {\n do {\n lastToken = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSPersistentHistoryToken.self, from: tokenData)\n } catch {\n Logger.error(" ###\\(#function): Failed to unarchive NSPersistentHistoryToken. Error = \\(error)")\n }\n }\nRun Code Online (Sandbox Code Playgroud)\n处理这些更改的代码:
\n// https://developer.apple.com/documentation/coredata/consuming_relevant_store_changes\n @objc func updatedFromCKCD(_ notifiction: Notification) {\n let fetchHistoryRequest = NSPersistentHistoryChangeRequest.fetchHistory(\n after: lastToken\n )\n \n let context = container.newBackgroundContext()\n guard\n let historyResult = try? context.execute(fetchHistoryRequest)\n as? NSPersistentHistoryResult,\n let history = historyResult.result as? [NSPersistentHistoryTransaction]\n else {\n Logger.error("\xe2\x9b\x88 Could not convert history result to transactions")\n assertionFailure()\n return\n }\n Logger.debug("\xe2\x9b\x88 Found cloud changes since: \\(self.lastToken?.description ?? "nil")")\n \n DispatchQueue.main.async {\n // look for particular set of changes which require the user to take action\n ...\n }\n }\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
355 次 |
| 最近记录: |