1

您好我正在尝试创建一个 NSOperaion 队列来下载一堆 PDF 文件。但它不起作用。NSURLConnection 没有调用委托方法,因为我将它们放在 NSOperation 队列中......任何替代方法或解决方案???

- (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];
}
4

3 回答 3

3

看看这里,这是一个对我有帮助的教程,所以我收藏了它

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

于 2010-10-04T20:32:46.137 回答
1

我真的看不出代码有问题,但这可能是线程问题。NSOperationQueue 通过 Grand Central Dispatch 创建一个线程来运行操作。如果 NSURLConnection 然后也尝试创建一个线程,它可能会导致问题 - 我不确定一个线程是否可以是子线程的子线程。

您可以执行 sendSynchronousRequest: 以便它保留在您在 NSOperationQueue 中创建的线程中,看看是否效果更好。

于 2010-10-04T20:31:11.527 回答
0

NSURLConnection 需要一个正在运行的 NSRunLoop 才能运行。如果您在 NSRunLoop 未运行的线程上调用 NSURLConnection 方法,则 NSURLConnection 将永远不会运行。NSOperationQueue 创建的工作线程没有运行它们的 NSRunLoops。你也不能保证当 NSURLConnection 收到来自服务器的响应时线程仍然存在。

从后台线程调用 NSURLConnection 方法很好,但它需要是一个可以保证其生命周期的线程,并且它需要运行它的 NSRunLoop。

于 2012-06-20T17:42:43.437 回答