未调用iOS dispatch_async和NSURLConnection委托函数

时间:2012-01-20 12:16:38

标签: objective-c ios nsurlconnection nsrunloop

我认为,我已经编辑了这篇文章,使其更易于阅读。

我需要在dispatch_async块中完成一些密集的字符串操作后调用NSUrlConnection。

我调用的URL上有.htaccess身份验证,因此我无法使用同步连接。

但是没有调用NSURLConnection委托方法。我知道在浏览器中大约5秒后加载了URL,并且我使用一个没有身份验证的简单URL测试了代码,但没有区别。

什么阻止调用委托方法?

此函数执行一些字符串操作,并需要一段时间才能完成:

- (void)performSearch {

    // set some defaults and work out if it is a valid search, setting bSearchOk

    if (bSearchOk) {

        // update some interface elements
        self.msgBox.text = @"Translating...";            
        self.plateInput.enabled = NO;
        self.searchProgress.hidden = NO;

        dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            // create a new search
            Search *oPlateSearch = [[Search alloc] initWithTerm:thisTerm];

            // ...
            // perform search... this calls a variety of slow and intensive functions
            // ...

            self.aFinalPlates = [oPlateSearch.aValidated copy];
            self.aCurrentPlates = [oPlateSearch.aFinals copy];        

            dispatch_async( dispatch_get_main_queue(), ^{                 
                [oPlateSearch release];              

                // make ajax call to check if plates can be bought
                [self getPrices];                 
            });
        });

    } else {
        // hide results
        self.searchResults.hidden = YES;
    }

}

这是在上面的块结束时调用的那个

/* call to get plate availability and prices */
-(void) getPrices {
    // set return message
    self.msgBox.text = @"Getting prices and availability";

    // ...
    // then I build my strRequest var, which is a valid working URL
    // ...

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strRequest]];

    NSURLConnection *loginConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

    NSLog('This will get logged');

    if(loginConnection) {
        NSLog('This will also get logged');
        self.jsonSearchResponse = [[[NSMutableData data] retain] autorelease];
        NSLog('And this will get logged, so it's not throwing errors');
    } else {
        NSLog(@"Failed to get search results");
    }
}

更新:我也试过这个,因为它是另一个类似问题的答案,但它没有奏效:

NSURLConnection *loginConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[loginConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
[loginConnection start];

基于这个问题:Why NSURLConnection delegate methods don't get called, when using the global dispatch queue?

3 个答案:

答案 0 :(得分:4)

来自iphonedevsdk.com论坛的某人为我解答了这个问题:

http://www.iphonedevsdk.com/forum/iphone-sdk-development/97415-dispatch_async-nsurlconnection.html

答案是使用:

 [self performSelectorOnMainThread:@selector(getPrices) withObject:Nil waitUntilDone:NO];

答案 1 :(得分:4)

我已经发布了一篇SO帖子,其中展示了如何将NSURLConnectiondispatch_async一起使用并配置NSRunLoop

NSURLConnection blocking wrapper implemented with semaphores

您感兴趣的代码是:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [NSURLConnection connectionWithRequest:request delegate:self];

    while(!self.finished) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }
});

并在connectionDidFinishLoading中,将finished设置为YES:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    self.finish = YES;
}

答案 2 :(得分:0)

我认为你是自动释放连接而不保留对它的任何引用,因此它会耗尽内存。删除自动释放呼叫,看看问题是否消失。如果是这样,只需找到一种方法来释放连接,这样它就不会泄漏。