【问题标题】:How to do incremental writing for UIDocument in iCloud?如何在 iCloud 中为 UIDocument 进行增量写入?
【发布时间】:2014-02-20 23:34:37
【问题描述】:

我在 iCloud 通用容器中有 UIDocument,我需要在保存文档时将数据附加到文件中。我根据 UIDocument 文档覆盖 readFromURL::writeContents::::: 方法:

-(BOOL) writeContents:(id)contents toURL:(NSURL*)url forSaveOperation:(UIDocumentSaveOperation)saveOperation originalContentsURL:(NSURL*)originalContentsURL 错误:(NSError *__autoreleasing *)outError { NSFileCoordinator* coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:self]; NSError* 错误 = 零; [协调器坐标WritingItemAtURL:url选项:0错误:&错误byAccessor:^(NSURL *newURL){ NSData* 数据 = 内容; //正确的,非空的NSData ///[data writeToFile:newURL :] 有效,但覆盖原始文件 NSOutputStream* 流 =[[NSOutputStream alloc] initWithURL:newURL append:YES]; 如果(流) { NSInteger 写入 = [流写入:data.bytes maxLength:data.length]; 如果(写!= data.length) { //这里失败,写成== -1 NSLog(@"向 UIDocument 写入数据失败:%@,错误:%@", newURL, stream.streamError); } } 别的 { NSLog(@"向 iCloudDocument 写入数据失败:%@", newURL); } }]; 如果(错误) { NSLog(@"协同写入失败%@,错误:%@", url, error); *outError = 错误; } 返回错误 == nil; }

Accessor 块有不同的 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 文件不存在,我无法追加数据,只能创建包含所有文档内容的文件。

文档编辑代码:

NSURL* url = [self.containerURL URLByAppendingPathComponent:kCloudDocumentName]; MyDocument* 文档 = [[MyDocument alloc] initWithFileURL:url]; [文档 openWithCompletionHandler:^(BOOL 成功) { 如果(成功) { //更新一些文档数据 [自我更新数据:文档完成:无]; [文档 closeWithCompletionHandler:^(BOOL 成功) { //这里失败了! }]; } }];

MyDocument 存在于url 的无处不在的容器中,并且文档处于正常状态。

在这种情况下如何进行增量写作?怎么了?

【问题讨论】:

  • 我也面临同样的问题。任何解决方案?

标签: ios iphone objective-c icloud uidocument


【解决方案1】:

更改 UIDocumnet 中的数据后,您可以使用:

-[UIDocumnet saveToURL:UIDocumnet.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:nil];

不确定,它是否正确,但它适用于我的应用程序。如有错误,请大神指正。

您可能需要在您的 UIDocumnet 子类中覆盖此方法:

- (id) contentsForType:(NSString *)typeName error:(NSError **)outError

【讨论】:

  • 我使用[UIDocument saveToURL::] 创建文档。如果文档已经存在,我会通过[UIDocument updateChangeCount:], and [UIDocument closeWithCompletionHandler:]`调用自动保存来使用自动保存。
  • 我有自己的 - (id) contentsForType:(NSString *)typeName error:(NSError **)outError 并简单地返回带有存档文档内容的非空 NSData
猜你喜欢
  • 1970-01-01
  • 2014-11-18
  • 2018-03-13
  • 2023-03-20
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
  • 2019-10-12
相关资源
最近更新 更多