2012-10-30 79 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。 –

相關問題