A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© hexue1027 中级黑马   /  2015-4-22 20:21  /  618 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 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_关东升


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马