从新线程设置时,连接不响应

时间:2010-02-25 08:49:27

标签: iphone multithreading connection

从新线程设置时,连接不响应:

代码1(回复正常):

[self setConnection];
}
- (void)setConnection{
    NSLog(@"setting myConnection with request");
    myConnection = [[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:requestURL] delegate:self] autorelease];   
}

Log 1:
2010-02-25 10:44:04.384 Untitled[1002:207] setting myConnection with request
2010-02-25 10:44:06.093 Untitled[1002:207] didReceiveResponse
2010-02-25 10:44:06.094 Untitled[1002:207] didReceiveData
2010-02-25 10:44:06.094 Untitled[1002:207] DidFinishLoading

Code 2:
[NSThread detachNewThreadSelector:@selector(setConnection) toTarget:self withObject:nil];   
}
- (void)setConnection{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSLog(@"setting myConnection with request");
    myConnection = [[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:requestURL] delegate:self] autorelease];   
    [pool release];
}

Log 2:
2010-02-25 10:40:50.280 Untitled[972:4003] setting myConnection with request


Delegates:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  { 
    NSLog(@"didReceiveResponse");
} 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  { 
    NSLog(@"didReceiveData");
}  
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"didFailWithError");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    NSLog(@"DidFinishLoading");
}

为什么? 发送请求的正确方法是什么?接收响应 - 不冻结主线程/ UI。

2 个答案:

答案 0 :(得分:2)

来自NSURLConnection文档:

  

使连接正常工作   调用线程的运行循环必须是   在默认的运行循环中运行   模式。

  

请注意,这些委托方法会   在启动的线程上调用   异步加载操作   关联的NSURLConnection对象。

在你的情况下,可能发生的是线程在你的类实际执行它的所有代码之前完成。

阅读本文以获取有关如何启动运行循环的解决方案: http://www.depl0y.com/2009/02/20/nsurlconnection-in-its-own-thread/

或者,创建第二个线程并通过执行NSURLConnection sendSynchronousRequest:returningResponse:error完全避免runloops问题,在调用线程中不需要特殊的线程或运行循环配置。
不要忘记通过performSelectorInMainThread:

回拨主线程

答案 1 :(得分:1)

它不起作用,因为线程在您的类实际执行所有代码之前完成。 您现在需要做的就是启动运行循环,这样线程就不会退出,下载就可以了。

[[NSRunLoop currentRunLoop] run];

你可以在这里看到这个迷你tuto:NSURLConnection in it's own thread