iCloud文檔在保存的過程中難免會發生沖突,我們必須要有一套解決沖突的策略。策略的采用要根據用戶的需求而定,有的簡單有的復雜,最簡單的是直接使用當前版本覆蓋沖突版本。復雜的策略,例如:如果是兩個文本文件沖突,可以將兩個沖突點列出來,讓用戶來判斷再進行保存。
我們采用的策略是使用當前版本覆蓋以前的版本。解決沖突首先需要在updateUbiquitousDocuments:方法中注冊UIDocumentStateChangedNotification通知:
[cpp]
//當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]; ⑧
}
//當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]; ⑧
}