2016-07-14 51 views
0

我不明白爲什麼我的數組超出了界限。我把源項目到一個數組「imageArray」,它給了我致命的錯誤繼承人代碼指數越界swift

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BlogPost 

    let blogPost: BlogPost = blogPosts[indexPath.row] 
    cell.textLabel?.text = blogPost.postTitle 
    // cell.textLabel?.text = blogPost.postImageLink 
    if cell.postImage?.image == nil { 
    // let cache = ImageLoadingWithCache() 
     // cache.getImage(self.postImageLink, imageView: cell.postImage, defaultImage: "IMG_0079")} 
    if cell.postImage?.image == nil { 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 

     // retrieve image from url 
     let image = UIImage(data: NSData(contentsOfURL: NSURL(string:self.postImageLink)!)!) 
     self.imageArray.append(image!) 
     dispatch_async(dispatch_get_main_queue(), { Void in 
      // set image in main thread 

      cell.postImage?.image = self.imageArray[indexPath.row] 
     }) 
    } 
    } else { 
      cell.postImage?.image = UIImage(named: "IMG_0079") 
     } 

    } 

    return cell 
} 

具體的錯誤是在這裏

cell.postImage?.image = self.imageArray[indexPath.row] 

什麼想法?

+0

嘗試使用此擴展名UIImageView http://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift/27712427#27712427 –

+0

我會猜測這是因爲'indexPath'是當閉包被創建時被捕獲,然後在閉包被調用時'indexPath.row'變得陳舊和越界。更不用說你在那裏強制展開了很多東西,如果其中一些'Optional'沒有設置呢?測試並正確拆包它們! – ColGraff

回答

0

您的TableView中的行數必須與您的imageArray計數值相同。這意味着:如果你有10個單元並且只有9個圖像,那麼第10個單元會尋找不存在的第10個圖像。

可以肯定的是,錯誤不會再出現,只設置你的前面添加以下if語句

if (indexPath.row < self.imageArray.count) { } 

或者作爲ColGraff

的防護語句會更好表明你在做什麼

guard indexPath.row < self.imageArray.count else { return } 

在您的單元版之前。

這兩個解決方案應該可以避免你的麻煩。

+0

'guard'聲明可以更好地表明你在做什麼:'guard indexPath.row ColGraff

+0

是的,當然,但兩者都可以工作!他決定是否喜歡使用它!很多不同的解決方案工作^^ –

+0

當然!我添加了評論,因爲這是使用'guard'的好地方,這種情況是它被添加到語言中的一個原因。 – ColGraff