我有一堆服务器请求,我可以异步运行,但我需要等待他们都完成之前,我继续。试图等待一组NSURLConnections来完成
dispatch_group_async它似乎很合理,但我不能得到它的工作。它要么永远封锁,要么根本不封锁。我的最新尝试,看起来像....
dispatch_group_t group;
- (void)cleanRoom {
NSAssert(![NSThread isMainThread], @"not on main thread.");
group = dispatch_group_create();
for (Junk *thing in myRoom) {
// take it off the current thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// register code against group
dispatch_group_enter(attachmentGroup);
NSURLConnectionWrapper *wrapper = [[NSURLConnectionWrapper alloc] init];
wrapper.delegate = self;
[wrapper sendRequestFor:thing];
}];
}
// wait till the stuff is the group is done
dispatch_group_wait(attachmentGroup, DISPATCH_TIME_FOREVER);
NSLog(@"waiting complete!!!!");
// process the results now that I have them all
}
- (void)wrapperConnectionDone {
// do a bit more junk
dispatch_group_leave(group);
}
这将导致它永远阻塞,因为NSURLConnectionDelegate
和NSURLConnectionDataDelegate
方法永远不会获取调用。我假设我已经以某种方式阻止他们的线程,但使用NSLog
我可以确认NSURLConnection
是在与我的cleanRoom
方法不同的线程。
我读了一些关于没有运行循环来做回调的其他线程,所以我尝试了像connection setDelegateQueue:[NSOperationQueue mainQueue]]
和[[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]]
之类的东西,但是没有什么不明显的效果。
+ sendAsynchronousRequest:queue:completionHandler:
不适合我,我有一些丑陋的认证。我已经看到了一些很好的例子,但我没有适应。
我很明显缺少一些基本位,但我找不到它。
我一直在使用NSOperations来做到这一点,当队列变为0时,你知道你已经完成了。简单易用的代码 - 一个操作管理器和一个NSOperation示例子类,可以在这里找到:github.com/dhoerl/NSOperation-WebFetches-MadeEasy。在OperationsRunner.h中有一个“如何做”。也就是说github上有很多这样的操作。 –
你有一个很好的观点。早些时候,我在'NSURLConnection'上使用'setDelegateQueue:[NSOperationQueue mainQueue]]'来代替更多的简化代码,而不是在调用代码中创建额外的GCD块。现在我已经开始使用GCD,我可能会返回并将其切换回来以方便阅读。在很多情况下,NSOperation和GCD可以用来做同样的事情。对于其他谁可能遵循,http://stackoverflow.com/questions/10373331/nsoperation-vs-grand-central-dispatch是相当描述。 – DBD