2012-10-30 68 views
0

我有以下代码,它不起作用。它背后有什么工作吗?NSOperation和NSOperationQueue不起作用

[operationQueue addOperationWithBlock:^{ 
     imageData = [NSData dataWithContentsOfURL:imageURL]; 
     [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
      UIImage *image = nil; 

      if(imageData){ 
       UIImage *image = [UIImage imageWithData:imageData]; 
       cell.imageView.image = image; 
      } 
     }]; 
    }]; 

即使我创建的NSOperation的一个子类,然后ALLOC初始化它,它不工作,我认为它的方式。我总是不得不启动NSOperation的子类才能运行,但我想发送启动消息给NSOperation会在主线程中运行它,而不是在后台线程中运行。

+3

的输出是什么?如果您需要帮助,请告诉我们触发了什么错误。我们不是读心者。 – Steven

+0

你有没有试过把断点放在行'imageData = [NSData dataWithContentsOfURL:imageURL];''和'UIImage * image = nil;'?知道这将使我们知道你的程序是否执行过你添加到两个不同'NSOperationQueue'中的块​​。如果你在'UIImage * image = nil;'处打断,请打印'[imageData length]'。 –

+0

这不适用于我,我无法以这种方式加载图像。我有空的回应,似乎下载图像的块没有被调用。 – Sandeep

回答

1

我要添加使用GCD的替代解决方案:

backgroundQueue = dispatch_queue_create("com.razeware.imagegrabber.bgqueue", NULL); 
dispatch_async(backgroundQueue, ^{ 
          /* put the codes which makes UI unresponsive like reading from network*/ 
         imageData = [NSData dataWithContentsOfURL:imageURL]; 
         ..... ; 
         dispatch_async(dispatch_get_main_queue(),^{ 
             /* do the UI related work on main thread */ 
             UIImage *image = [UIImage imageWithData:imageData]; 
             cell.imageView.image = image; 
             ......; }); 
            }); 
dispatch_release(backgroundQueue); 

让我知道这是否一个帮助过你;)

Reference

+0

很难决定哪个实现看起来更干净。我喜欢这两个。这一个缺点是需要记住dispatch_release()。 –

+0

以及gcd总是看起来令人愉快的我。至少,地下将发生什么是显然可以理解的。我只是想用NSOperationQueue和NSOperation测试一些功能,但我几乎没有成功。 – Sandeep

+0

是的,我更喜欢GCD。 –

相关问题