【问题标题】:Opening Several UIDocuments in Succession and Waiting for Them to Finish连续打开几个 UIDocument 并等待它们完成
【发布时间】:2013-10-23 09:38:19
【问题描述】:

我无法理解 UIDocument 异步打开的方式。我有一系列用户创建的 UIDocument。当用户按下按钮时,我需要打开一些文档,从中提取一些字符串,然后将这些字符串连接到一个新文件中。

我有一个数组来跟踪需要打开哪些文档。我的想法是我应该遍历数组,打开每个文档,并将其内容附加到NSMutableString。问题是openWithCompletionHandler 异步执行其工作,因此循环前进并结束,在文档被打开(并再次关闭)之前返回一个空字符串。

这里有一点代码:

__block NSMutableString *combinedString;

for (entryClass *entry in documentList)
{
    MyDocumentClass *document = [[MyDocumentClass alloc] initWithFileURL:[entry fileURL]];

    if ([document documentState] & UIDocumentStateClosed) {
        [document openWithCompletionHandler:^(BOOL success) {

            if (success) {
                [combinedString appendString:[document documentBody]];
            }

            [document closeWithCompletionHandler:nil];
        }];
    }
}

NSLog(@"Combined String: %@", combinedString);

很自然地,combinedString 会返回为空,因为在后台打开文档时循环结束。我可以将文档处理移动到它自己的返回字符串的方法,但我认为这仍然会在文档被读取之前返回。我大概必须设置一个进度指示器并让用户等待——这可能没问题。

【问题讨论】:

    标签: ios objective-c uidocument


    【解决方案1】:

    您可以使用调度组来做到这一点。请参阅Low-Level Concurrency APIs 上的“组”和“将 dispatch_group_t 与现有 API 一起使用”部分。

    【讨论】:

      【解决方案2】:

      我不得不做一些非常相似的事情,而不是深入研究低级功能,我用openDocumentWithContentsOfURL:display:completionHandler: 打开了文档。因为它将打开的文档传递给completionHandler,所以您可以从文档中提取数据,然后在completionHandler 块中关闭它。

      这假设您不关心文档将其数据写入字符串的顺序,因为理论上不同文档的 completionHandlers 可以按任何顺序运行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-13
        • 2019-02-23
        • 2021-05-25
        相关资源
        最近更新 更多