2012-04-18 73 views
0

我將圖像異步加載到UITableView中的單元格上。代碼如下所示:如果調用對象被釋放,調度線程會發生什麼?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

// after getting the cell.. 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     NSString *imageUrl = [someMethodToGetImageUrl]; 
     NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL imageUrl]]; 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      cell.imageView.image = [UIImage imageWithData:imageData]; 
      [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone]; 
     }); 
    }); 

} 

我的問題涉及到它觸發關閉後調度會發生什麼,如果這的tableView被釋放(例如彈出的navigationController棧),但線程完成嘗試設置單元格的圖像之前。細胞也將被釋放,並試圖對該細胞做東西會導致崩潰,不是嗎?

我一直在使用上面的代碼崩潰。如果我Segue公司進入這個的tableView然後立刻退了出去,我上線崩潰:

[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone]; 

如果我將其更改爲:

[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone]; 

的崩潰消失,這並沒有真正感覺到我。有人可以向我解釋爲什麼會出現這種情況嗎?謝謝。

+0

ARC是否啓用?以及如何定義屬性(例如,弱,強,複製等) – 2012-04-18 21:22:57

+0

是的,啓用了ARC,並且我對第二個問題的答案不瞭解。我的代碼片段中沒有任何變量是屬性。他們只是通過[alloc]方法分配。我是初學者,這是否回答你的問題? – Steven 2012-04-18 21:28:08

+0

我確實有一個屬性,我在此代碼段中簡化/遮蔽了。 'someMethodToGetImageUrl'方法實際上是一個聲明爲(非原子,強大)的屬性對象中的實例方法。 – Steven 2012-04-18 21:31:18

回答

2

任何可能使塊超出其原始範圍的例程都需要複製它。 dispatch_async()呢。

複製塊時,它保留它引用的任何對象指針變量。如果該塊以實例變量的形式隱式訪問self,則它將保留self。它持有這些引用,直到它自己發佈。

在您的示例中,cell,imageData,indexPathtableView都保留,直到塊完成。

相關問題