2016-07-06 40 views
2

我正在努力讓自己的頭部圍繞我得到的EXEC_BAD_ACCESS錯誤。代碼如下:EXEC_BAD_ACCESS填充dispatch_async中的單元格內容

// Update the cell 
dispatch_async(dispatch_get_main_queue(), { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("customCell", forIndexPath: indexPath) as! CustomCollectionViewCell // crash here 
    cell.image.image = image 
    if(collectionView.numberOfItemsInSection(0) > indexPath.row) { 
     self.collectionView.reloadData() 
    }    
}) 

代碼被設計爲異步填寫collectionViewCell的圖像中接收來自NSURLSession.dataTaskWithRequest的響應之後。

崩潰發生在let cell =行,因爲(我相信)indexPath不再存在(因爲我已經改變了collectionView的內容)。我不知道如何檢查,但。

我認爲沿if let cell =行的東西會工作,但我想我誤解了這是如何工作的。從閱讀其他文章,我可以看到,你不能把代碼放在try/catch塊中。

任何想法?提前謝謝了!

+0

你在'cellForRow ...'中做了這個嗎?你應該那樣做 – tbilopavlovic

+0

是的 - 這只是其中的一小部分。這個想法是行將顯示,然後其中的圖像將被異步填充,以便滾動等順利。 – Ben

+0

好的,但你爲什麼要這樣做:let cell = ....'? – tbilopavlovic

回答

2

collectionView.dequeueReusableCellWithReuseIdentifier用於重複使用func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell中的單元格,而不是手動創建它們。你在這裏想要的是檢索單元格,而不是重用它,所以你應該使用:cellForItemAtIndexPath(_ indexPath: NSIndexPath)

+0

排序 - 「如果let cell = collectionView.cellForItemAtIndexPath(indexPath)as? RewardCollectionViewCell {' - 感謝您的幫助! – Ben

相關問題