索引迅速超出范围

时间:2016-07-14 00:27:54

标签: arrays swift uiimage indexoutofboundsexception

我无法弄清楚为什么我的阵列超出范围。我将饲料项目放入一个数组" imageArray"它给了我致命的错误继承人代码

   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]

任何想法?

1 个答案:

答案 0 :(得分:0)

您的TableView节中的行数必须与imageArray计数具有相同的值。这意味着:如果你有10个单元格,只有9个图像,那么第10个单元格将查找不存在的第10个单元格。

为了确保错误不再出现,只需在设置单元格之前添加以下 if语句

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

ColGraff

  

警卫声明会更好地表明你正在做什么

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

在您的手机版之前。

这两种解决方案应该避免任何麻烦。

相关问题