黑马程序员技术交流社区

标题: 解决iCloud文档存储过程 [打印本页]

作者: hexue1027    时间: 2015-4-22 20:21
标题: 解决iCloud文档存储过程
本帖最后由 hexue1027 于 2015-4-22 20:25 编辑

iCloud文档在保存的过程中难免会发生冲突,我们必须要有一套解决冲突的策略。策略的采用要根据用户的需求而定,有的简单有的复杂,最简单的是 直接使用当前版本覆盖冲突版本。复杂的策略,例如:如果是两个文本文件冲突,可以将两个冲突点列出来,让用户来判断再进行保存。


我们采用的策略是使用当前版本覆盖以前的版本。解决冲突首先需要在updateUbiquitousDocuments:方法中注册UIDocumentStateChangedNotification通知:


  1. //当iCloud中的文件变化时候调用
  2. - (void)updateUbiquitousDocuments:(NSNotification *)notification {

  3. if (_myCloudDocument) {

  4. //注册CloudDocument对象到文档协调者,文档状态变化才能收到通知

  5. [NSFileCoordinator addFilePresenter:_myCloudDocument];      

  6. //注册文档状态变化通知

  7. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resolveConflict:)

  8. name:UIDocumentStateChangedNotification object:nil];        

  9. }

  10. }

  11. //文档冲突解决

  12. - (void)resolveConflict:(NSNotification *)notification {

  13. if (_myCloudDocument

  14. && _myCloudDocument.documentState == UIDocumentStateInConflict) {

  15. NSLog(@”冲突发生”);

  16. //文档冲突解决策略

  17. NSError *error;

  18. if (![NSFileVersion removeOtherVersionsOfItemAtURL: _

  19. myCloudDocument.fileURL error:&error]) {

  20. NSLog(@”移除其它的文档: %@”, [error localizedFailureReason]);

  21. return;

  22. }

  23. _myCloudDocument.contents = _txtContent.text;

  24. [_myCloudDocument updateChangeCount:UIDocumentChangeDone];   

  25. }

  26. [[NSNotificationCenter defaultCenter] removeObserver:self

  27. name:UIDocumentStateChangedNotification object:nil];

  28. //从文档协调者中解除CloudDocument对象

  29. [NSFileCoordinator removeFilePresenter:_myCloudDocument];     

  30. }
复制代码



出自《iOS网络编程与云端应用最佳实践》作者:关东升 @tony_关东升







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2