Sat*_*ran 6 nsoperation nsoperationqueue grand-central-dispatch ios
我正在尝试在特定函数中实现异步URL请求,我希望所有这些请求完成然后执行特定操作但操作先于请求,即在请求完成之前调用它.
dispatch_queue_t fetchQ = dispatch_queue_create("Featured Doc Downloader", NULL);
dispatch_async(fetchQ, ^{
[self myAsyncMultipleURLRequestFunction];
dispatch_sync(dispatch_get_main_queue(), ^{
[self updateUIFunction];
});
});
-(void)myAsyncMultipleURLRequestFunction
{
for (int i=0; i<count; i++)
{
NSURLConnection *loginConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
}
}
Run Code Online (Sandbox Code Playgroud)
现在在myAsyncMultipleURLRequestFunction完成所有请求之前调用updateUIFunction.也尝试使用NSOperaitonQueue,但不能做我真正想要的.
[_operationQ addOperationWithBlock: ^ {
for (int i=0; i<count; i++)
{
NSURLConnection *loginConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
}
}
[[NSOperationQueue mainQueue] addOperationWithBlock: ^ {
// updating UI
[self updateUIFunction];
}];
}];
Run Code Online (Sandbox Code Playgroud)
我知道这很简单,但我的时间不多了,任何帮助都表示赞赏.
aLe*_*ion 10
@tkanzakic正走在正确的道路上.要使用的正确构造是dispatch_group_t.但实施可以改进.通过使用信号量,您可以异步启动所有下载,并且仍然确保没有太多并发运行.下面是一个代码示例,说明了如何使用dispatch_group_t并使所有下载并行:
dispatch_queue_t fetchQ = dispatch_queue_create("Featured Doc Downloader", NULL);
dispatch_group_t fetchGroup = dispatch_group_create();
// This will allow up to 8 parallel downloads.
dispatch_semaphore_t downloadSema = dispatch_semaphore_create(8);
// We start ALL our downloads in parallel throttled by the above semaphore.
for (int i=0; i<count; i++) {
dispatch_group_async(fetchGroup, fetchQ, ^(void) {
dispatch_semaphore_wait(downloadSema, DISPATCH_TIME_FOREVER);
NSURLConnection *loginConnection = [[NSURLConnection alloc] initWithRequest:requestArray[i] delegate:self];
dispatch_semaphore_signal(downloadSema);
});
}
// Now we wait until ALL our dispatch_group_async are finished.
dispatch_group_wait(fetchGroup, DISPATCH_TIME_FOREVER);
// Update your UI
dispatch_sync(dispatch_get_main_queue(), ^{
[self updateUIFunction];
});
// Release resources
dispatch_release(fetchGroup);
dispatch_release(downloadSema);
dispatch_release(fetchQ);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1743 次 |
| 最近记录: |