Reputation: 103
i can't figure out why my array is out of bounds. i put the feed items into an array "imageArray" and it gives me fatal error heres code
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
}
specifically the error is here
cell.postImage?.image = self.imageArray[indexPath.row]
any ideas?
Upvotes: 0
Views: 3643
Reputation: 298
Your TableView number of rows in section must have the same value as your imageArray count. That signify : if you have 10 cells and only 9 images, the 10th cell would look for the 10th image which do not exist.
To be sure that the error does not appear anymore, just add the following if statement before setting your cell :
if (indexPath.row < self.imageArray.count) { }
Or as ColGraff said
A guard statement would better indicate what you're doing
guard indexPath.row < self.imageArray.count else { return }
Before your cell edition.
Those two solutions should avoid you any troubles.
Upvotes: 1