2010-02-25 5 views
0

새 스레드에서 설정에 beeing 때 응답하지 않습니다연결이 연결이 새 스레드에서 설정에 beeing 때 응답하지 않는

코드 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를 고정하지 않고 응답을 수신하는 것입니다.

답변

1

클래스가 실제로 모든 코드를 실행하기 전에 스레드가 완료되기 때문에 작동하지 않습니다. 이제 실행 루프 만 시작하면 스레드가 종료되지 않고 다운로드가 작동 할 수 있습니다.

[[NSRunLoop currentRunLoop] run]; 

현재이 미니 TUTO 볼 수있는 다음있는 NSURLConnection 문서에서 NSURLConnection in it's own thread

2

:

호출 스레드의 실행 루프가 기본으로 운영 을해야 연결이 제대로 작동하려면를 루프 모드를 실행하십시오. 이러한 위임 방법은 관련있는 NSURLConnection 개체에 대해 비동기로드 작업을 시작한 스레드에서 호출됩니다

참고.

귀하의 경우, 클래스가 실제로 모든 코드를 실행하기 전에 스레드가 완료됩니다. http://www.depl0y.com/2009/02/20/nsurlconnection-in-its-own-thread/

또는 두 번째 스레드를 생성하고 모두 특별한 나사 또는 실행 루프 구성이없는 대한 NSURLConnection sendSynchronousRequest:returningResponse:error을 수행하여 runloops의 문제를 방지 :

실행 루프를 시작하는 방법에 대한 해결책이 읽기 호출 스레드에서 필요합니다.
performSelectorInMainThread:

을 통해 기본 스레드로 다시 전화하는 것을 잊지 마십시오.
관련 문제