Question

Hi I am trying to create a NSOperaion Queue to download a bunch of PDF files. But it doesnt work. The delegate methods dont get called for NSURLConnection since i put them in NSOperation queue.... any alternatives or solution???

- (void) loadData {
 NSOperationQueue *queue = [NSOperationQueue new];
 NSInvocationOperation *operation;
 for(int i=0;i<[self.pdfArray count];i++){
  NSString *url = [NSString stringWithFormat:@"http://www.somelink.com/%@.pdf",[self.pdfArray objectAtIndex:i]];
  operation = [[NSInvocationOperation alloc] initWithTarget:self 
               selector:@selector(loadDataWithOperation:) 
                 object:url];

  [queue addOperation:operation];
  [operation release];
 }
}

- (void) loadDataWithOperation:(NSString *) url{

 // Create the request.

    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
            cachePolicy:NSURLRequestUseProtocolCachePolicy
            timeoutInterval:60.0];

    NSURLConnection  *theDownload = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
}
Was it helpful?

Solution

take a look here, this is a tutorial that was helpful to me so I bookmarked it

http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/

OTHER TIPS

I can't really see a problem with the code but it might be a threading issue. NSOperationQueue creates a thread through Grand Central Dispatch to run the operation. If NSURLConnection then also tries to create a thread it might cause an issue - I'm not sure a thread can be a child of a child thread.

You could do an sendSynchronousRequest: so that it stays in the thread that you have created in the NSOperationQueue and see if that works better.

NSURLConnection needs a running NSRunLoop to function. If you call NSURLConnection methods on a thread whose NSRunLoop is not running, the NSURLConnection will never run. The worker threads that NSOperationQueue creates don't have their NSRunLoops running. Nor could you guarantee that the thread would still exist when the NSURLConnection received a response from the server.

It is fine to call NSURLConnection methods from a background thread, but it needs to be a thread whose lifetime you can guarantee and it needs to have its NSRunLoop running.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top