title: Asynchronous request to the server from background thread
body: <p>I've got the problem when I tried to do asynchronous requests to server from background thread. I've never got results of those requests. Simple example which shows the problem:</p>
  
  <pre><code>@protocol AsyncImgRequestDelegate
  -(void) imageDownloadDidFinish:(UIImage*) img;
  @end
  
  
  @interface AsyncImgRequest : NSObject
  {
   NSMutableData* receivedData;
   id&lt;AsyncImgRequestDelegate&gt; delegate;
  }
  
  @property (nonatomic,retain) id&lt;AsyncImgRequestDelegate&gt; delegate;
  
  -(void) downloadImage:(NSString*) url ;
  
  @end
  
  
  
  @implementation AsyncImgRequest
  -(void) downloadImage:(NSString*) url 
  {  
   NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
               cachePolicy:NSURLRequestUseProtocolCachePolicy
              timeoutInterval:20.0];
   NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
   if (theConnection) {
    receivedData=[[NSMutableData data] retain];
   } else {
   }  
  
  }
  
  - (void)connectionDidFinishLoading:(NSURLConnection *)connection
  {
    [delegate imageDownloadDidFinish:[UIImage imageWithData:receivedData]];
    [connection release];
    [receivedData release];
  }
  @end
  </code></pre>
  
  <p>Then I call this from main thread </p>
  
  <pre><code>asyncImgRequest = [[AsyncImgRequest alloc] init];
  asyncImgRequest.delegate = self; 
  [self performSelectorInBackground:@selector(downloadImage) withObject:nil];
  </code></pre>
  
  <p>method downloadImage is listed below:</p>
  
  <pre><code>-(void) downloadImage
  {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   [asyncImgRequest downloadImage:@"http://photography.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/Photography/Images/POD/l/leopard-namibia-sw.jpg"];
   [pool release];
  }
  </code></pre>
  
  <p>The problem is that method imageDownloadDidFinish is never called. Moreover none of methods  </p>
  
  <pre><code>- (void)connectionDidFinishLoading:(NSURLConnection *)connection
  - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response
  </code></pre>
  
  <p>are called. However if I replace</p>
  
  <pre><code> [self performSelectorInBackground:@selector(downloadImage) withObject:nil]; 
  </code></pre>
  
  <p>by </p>
  
  <pre><code> [self performSelector:@selector(downloadImage) withObject:nil]; 
  </code></pre>
  
  <p>everything is working correct. I assume that the background thread dies before async request is finished it job and this causes the problem but I'm not sure. Am I right with this assumptions? Is there any way to avoid this problem?</p>
  
  <p>I know I can use sync request to avoid this problem but it's just simple example, real situation is more complex.     </p>
  
  <p>Thanks in advance. </p>