开发者

Problems Getting Multiple NSURLConnections to Run in Parallel

I am am trying to get multiple NSURLConnections to run in parallel (synchronously), however if it is not running on the main thread (block of code commented out below) the URL connection doesn't seem to work at all (none of the NSURLConnection delegate methods are triggered). Here is the code I have (implementation file of an NSOperation subclass):

- (void)start
{
    NSLog(@"DataRetriever.m start");
    if ([self.DRDelegate respondsToSelector:@selector(dataRetrieverBeganExecuting:)])
        [self.DRDelegate dataRetrieverBeganExecuting:identifier];

开发者_StackOverflow    if ([self isCancelled]) {
        [self finish];
    } else {

        /*
        //If this block is not commented out NSURLConnection works, but not otherwise
        if (![NSThread isMainThread])
        {
            [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
            return;
        }*/

        SJLog(@"operation for <%@> started.", _url);

        [self willChangeValueForKey:@"isExecuting"];
        _isExecuting = YES;
        [self didChangeValueForKey:@"isExecuting"];

        NSURLRequest * request = [NSURLRequest requestWithURL:_url];
        _connection = [[NSURLConnection alloc] initWithRequest:request
                                                      delegate:self];
        if (_connection == nil)
            [self finish];
    } //not cancelled


}//start

Ran through it with a debugger, and after the end of this start method none of the NSURLConnection delegates trigger (I set breakpoints there). But on the main thread it works just fine. Any ideas of what's up? Thanks!


Background threads don't automatically have an active run loop on them. You need to start up the run loop after you create the NSURLConnection in order to get any input from it. Fortunately, this is quite simple:

[[NSRunLoop currentRunLoop] run];

When you say that you are running the connections synchronously, you are incorrect. The default mode of NSURLConnection is asynchronous -- it creates and manages a new background thread for you, and calls back to the delegate on the original thread. You therefore don't need to worry about blocking the main thread.

If you do actually want to perform a synchronous connection, you would use sendSynchronousRequest:returningResponse:error:, which will directly return the data. See "Downloading Data Synchronously" for details.


NSURLConnection needs an active run loop to actually work; the easiest way to ensure this is to just run it from the main thread.

Note that NSURLConnection normally runs asynchronously (and if you run one synchronously, what it really does is run one asynchronously on another thread and then block until that completes), so except for whatever processing you do in your delegate methods it shouldn't have much of an effect on UI responsiveness.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜