iOS網絡編程-解決iCloud文檔存儲過程中文檔衝突問題

爲大家介紹一下iOS網絡編程的教程。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]; ⑧


}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章