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]; ⑧
}