依次打开几个UIDocument并等待它们完成 [英] Opening Several UIDocuments in Succession and Waiting for Them to Finish
问题描述
我无法理解UIDocuments异步打开的方式.我有一系列用户创建的UIDocuments.当用户按下按钮时,我需要打开一些文档,从文档中拉一些字符串,然后将这些字符串连接到一个新文件中.
I'm having trouble getting my head around the way UIDocuments open asynchronously. I have a series of UIDocuments that the user has created. When the user presses a button I need to open some of the documents, pull some strings from them, and concatenate the strings into a new file.
我有一个数组,用于跟踪需要打开哪些文档.我的想法是我应该遍历数组,打开每个文档,并将其内容附加到NSMutableString
.问题在于openWithCompletionHandler
是异步进行的,因此循环在文件被打开(并再次关闭)之前前进并完成,返回一个空字符串.
I have an array that keeps track of which documents need to be opened. My thought was that I should loop through the array, open each document, and append its contents to an NSMutableString
. The problem is that openWithCompletionHandler
does its work asynchronously, so the loop marches ahead and finishes, returning an empty string, before the documents have been opened (and closed again).
这里有一些代码:
__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
返回为空.我可以将文档处理移至它自己的返回字符串的方法,但是我认为在读取文档之前,这仍然会返回.我大概必须设置一个进度指示器并让用户等待-可能没关系.
Naturally what happens is that combinedString
comes back empty because the loop finishes while the documents are opening in the background. I could move the document handling to its own method that returns a string but I think this will still return before the document is read. I'll presumably have to put up a progress indicator and make user wait--that's probably okay.
推荐答案
您可以对调度组执行此操作.请参见低级并发API .
You can do this with dispatch groups. See the sections "Groups" and "Using dispatch_group_t with Existing API" at Low-Level Concurrency APIs.
这篇关于依次打开几个UIDocument并等待它们完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!