2012-08-22 50 views
3

我有一堆服务器请求,我可以异步运行,但我需要等待他们都完成之前,我继续。试图等待一组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); 
} 

这将导致它永远阻塞,因为NSURLConnectionDelegateNSURLConnectionDataDelegate方法永远不会获取调用。我假设我已经以某种方式阻止他们的线程,但使用NSLog我可以确认NSURLConnection是在与我的cleanRoom方法不同的线程。

我读了一些关于没有运行循环来做回调的其他线程,所以我尝试了像connection setDelegateQueue:[NSOperationQueue mainQueue]][[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]]之类的东西,但是没有什么不明显的效果。

+ sendAsynchronousRequest:queue:completionHandler:不适合我,我有一些丑陋的认证。我已经看到了一些很好的例子,但我没有适应。

我很明显缺少一些基本位,但我找不到它。

+1

我一直在使用NSOperations来做到这一点,当队列变为0时,你知道你已经完成了。简单易用的代码 - 一个操作管理器和一个NSOperation示例子类,可以在这里找到:github.com/dhoerl/NSOperation-WebFetches-MadeEasy。在OperationsRunner.h中有一个“如何做”。也就是说github上有很多这样的操作。 –

+0

你有一个很好的观点。早些时候,我在'NSURLConnection'上使用'setDelegateQueue:[NSOperationQueue mainQueue]]'来代替更多的简化代码,而不是在调用代码中创建额外的GCD块。现在我已经开始使用GCD,我可能会返回并将其切换回来以方便阅读。在很多情况下,NSOperation和GCD可以用来做同样的事情。对于其他谁可能遵循,http://stackoverflow.com/questions/10373331/nsoperation-vs-grand-central-dispatch是相当描述。 – DBD

回答

2

NSURLConnection需要在具有处理后的运行循环的线程上运行。最简单的这样的线程是主线程。所以只需dispatch_async这些连接创建到dispatch_get_main_queue()和其余的dispatch_group逻辑应该没问题。请记住,委托方法将主线程(从NSURLConnection概述)上被称为:

这些委托方法被称为启动该异步加载操作相关的NSURLConnection的对象的线程上。

+0

太棒了,它的工作。事实证明这是一个复杂的问题。我在另一个进程中不知不觉地阻塞了我的主线程,所以即使我在运行循环中将它们放在主线程上,也不会进行NSURLConnectionDelegate调用。你回答解决了这个问题,让我看看对方的位置。 – DBD