2016-07-14 49 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