iCloud文档在保存的过程中难免会发生冲突,我们必须要有一套解决冲突的策略。策略的采用要根据用户的需求而定,有的简单有的复杂,最简单的是 直接使用当前版本覆盖冲突版本。复杂的策略,例如:如果是两个文本文件冲突,可以将两个冲突点列出来,让用户来判断再进行保存。
我们采用的策略是使用当前版本覆盖以前的版本。解决冲突首先需要在updateUbiquitousDocuments:方法中注册UIDocumentStateChangedNotification通知:
//当iCloud中的文件变化时候调用 - (void)updateUbiquitousDocuments:(NSNotification *)notification { … … if (_myCloudDocument) { //注册CloudDocument对象到文档协调者,文档状态变化才能收到通知 [NSFileCoordinator addFilePresenter:_myCloudDocument]; ① //注册文档状态变化通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resolveConflict:) name:UIDocumentStateChangedNotification object:nil]; ② } } //文档冲突解决 - (void)resolveConflict:(NSNotification *)notification { if (_myCloudDocument && _myCloudDocument.documentState == UIDocumentStateInConflict) { ③ NSLog(@”冲突发生”); //文档冲突解决策略 NSError *error; if (![NSFileVersion removeOtherVersionsOfItemAtURL: _ myCloudDocument.fileURL error:&error]) { ④ NSLog(@”移除其它的文档: %@”, [error localizedFailureReason]); return; } _myCloudDocument.contents = _txtContent.text; ⑤ [_myCloudDocument updateChangeCount:UIDocumentChangeDone]; ⑥ } [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDocumentStateChangedNotification object:nil]; ⑦ //从文档协调者中解除CloudDocument对象 [NSFileCoordinator removeFilePresenter:_myCloudDocument]; ⑧ }
出自《iOS网络编程与云端应用最佳实践》作者:关东升 @tony_关东升
相关推荐
- **iCloud 存储**:介绍了如何将 iCloud 集成到应用程序中,包括配置应用的 iCloud 权限、使用 iCloud 文档存储以及解决版本冲突等问题。 ### 结论 通过《iPhone App Programming Guide》这份详尽的文档,读者...
- **iCloud文档存储**:了解如何配置iCloud权限,以及如何在工作流程中整合文件呈现器,对于高效使用iCloud至关重要。 - **版本冲突策略**:当多个用户同时编辑同一文件时,合理处理版本冲突可以避免数据丢失。 - ...
- **iCloud文档存储**:支持文档级别的云同步,适用于文件共享场景。 - **iCloud容器与凭证**:了解如何配置iCloud容器ID和权限。 ### 13. 后台处理与Grand Central Dispatch - **多线程基础**:iOS应用通常运行在...
3. **文档同步**: iCloud Documents支持文档级别的同步,适合那些需要存储和编辑复杂文档的应用。 4. **容器共享**: ICloutKit提供了容器共享功能,使得来自不同应用程序的数据可以安全地共享在同一iCloud账户下。 ...