我有UClocument在iCloud無處不在的容器中,我需要在保存文檔時將數據附加到文件。我根據UIDocument文檔覆蓋readFromURL::
和writeContents:::::
方法:如何在iCloud中爲UIDocument進行增量書寫?
-(BOOL) writeContents:(id)contents toURL:(NSURL*)url forSaveOperation:(UIDocumentSaveOperation)saveOperation originalContentsURL:(NSURL*)originalContentsURL error:(NSError *__autoreleasing *)outError { NSFileCoordinator* coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:self]; NSError* error = nil; [coordinator coordinateWritingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) { NSData* data = contents; //correct, non-empty NSData ///[data writeToFile:newURL :] works, but overwrite original file NSOutputStream* stream =[[NSOutputStream alloc] initWithURL:newURL append:YES]; if (stream) { NSInteger written = [stream write:data.bytes maxLength:data.length]; if (written != data.length) { //failed here, written == -1 NSLog(@"Write data to UIDocument failed: %@, error: %@", newURL, stream.streamError); } } else { NSLog(@"Write data to iCloudDocument failed: %@", newURL); } }]; if (error) { NSLog(@"Coordinated write failed %@, error: %@", url, error); *outError = error; } return error == nil; }
訪問器塊具有不同的newURL,例如:
url: file:///private/var/mobile/Library/Mobile%20Documents/XXXXXXX~com~test~test/test.doc
newURL: file:///private/var/mobile/Applications/5631D484-7661-4E9E-A342-B25297FC0E18/tmp/(A%20Document%20Being%20Saved%20By%20test%20)/test.doc
。
[stream write::]
失敗,因爲newURL
文件dosn't存在,我不能追加數據,只能創建文件與所有文件的內容。
文獻編輯代碼:
NSURL* url = [self.containerURL URLByAppendingPathComponent:kCloudDocumentName]; MyDocument* document = [[MyDocument alloc] initWithFileURL:url]; [document openWithCompletionHandler:^(BOOL success) { if (success) { //update some document data [self updateData:document completion:nil]; [document closeWithCompletionHandler:^(BOOL success) { //failed here! }]; } }];
myDocument中無處不在容器存在於url
和文檔具有正常狀態。
在這種情況下,我如何才能做增量寫作?怎麼了?
我用'[UIDocument saveToURL ::]'用於創建文檔。如果文檔已經存在,我使用'[UIDocument updateChangeCount:]自動保存,''UIDocument closeWithCompletionHandler:]'自動保存呼叫。 –
我有自己的' - (id)contentsForType:(NSString *)typeName錯誤:(NSError **)outError',並簡單地返回帶有歸檔文檔內容的非空NSData –