Rob Sparks
Rob Sparks

Reputation: 77

Swift - Setting cell customImageView.image to nil causes error

I'm currently working on a news page for an app, and we have encountered an issue when attempting to set the cell's customImageView.image to nil, to ensure cells do not load another cell's image whilst it loads it's own:

cellForRowAtIndexPath (tableView)

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var requestImg: Alamofire.Request?

    var article : NewsItem
    article = filteredArticles[indexPath.row]
    let imageUrl = NSURL(string: article.image)

    if imageUrl == nil || article.image.isEmpty { newsCellIdentifier = "NewsCellNoImage" }
    else { newsCellIdentifier = "NewsCell" }

    let cell = self.tableView.dequeueReusableCellWithIdentifier(newsCellIdentifier) as! NewsCell

    if (imageUrl != nil || !article.image.isEmpty) {

        cell.customImageView.image = nil // < ISSUE HERE
        requestImg?.cancel()

            requestImg = Alamofire.request(.GET, article.image).responseImage() {
                (request, _, image, error) in
                if error == nil && image != nil {
                    cell.customImageView.image = image
                }
            }
    }

    cell.titleLabel.text = article.title
    cell.categoryLabel.text = article.category

    return cell
}

NewsCell.Swift

class NewsCell: UITableViewCell {

@IBOutlet var titleLabel: UILabel!
@IBOutlet var customImageView: UIImageView!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var articleTime: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}
}

The issue arrives when calling cell.customImageView.image = nil, where I get this: fatal error: unexpectedly found nil while unwrapping an Optional value.

Everywhere i've looked, this is the correct way to reset the image of an UIImageView, so any help where i'm going wrong would be greatly appreciated.

Upvotes: 0

Views: 286

Answers (1)

&#214;zg&#252;r Ersil
&#214;zg&#252;r Ersil

Reputation: 7013

@IBOutlet var customImageView: UIImageView! defining unwrapping value with using ! here causes a problem. Because if you cast the value with ! that means it can not be nil

Making it optional will solve the problem

@IBOutlet var customImageView: UIImageView?

Upvotes: 1

Related Questions