在打开可选值时无,但在打印期间存在值

时间:2016-01-11 18:28:00

标签: ios swift uiimage tableview nsurl

当我想在m单元格中设置图片时,我的TableViewController有一种奇怪的情况。我的细胞类是:

  

class TableViewCell

class TableViewCell: UITableViewCell {

/* OUTLETS */

@IBOutlet weak var pictureInRowOutlet: UIImageView!
@IBOutlet weak var postDataOutlet: UILabel!
@IBOutlet weak var titleOutlet: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization cod
} 

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    // Configure the view for the selected state
}
}//end of class
  

类MyTableView

class MyTableView: UITableViewController{

var data:[[String:String]]? // data load from serwer    

//code we don't need

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

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell

// now I want to set up picture in row

let urlAdressPhoto = (data?[indexPath.item]["picture"])! 
// here, when I print urlAdressPhote I see correct value as String

cell.pictureInRowOutlet.image = UIImage(data: NSData(contentsOfURL: NSURL(string: urlAdressPhoto)!)!)
 // in this moment I recive an information about "unexpectedly found nil while unwrapping an Optional value". 

return cell

}

有人可以告诉我为什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

你强行打开至少3种不同的东西。在这一行中,

let urlAdressPhoto = (data?[indexPath.item]["picture"])! 

你强行解开(data?[indexPath.item]["picture"])并且你很幸运。它不是nil。你赌博并赢了。

也许你的成功让人陶醉,你决定加倍......在这里,你强行在一个陈述中解开两次:

UIImage(data: NSData(contentsOfURL: NSURL(string: urlAdressPhoto)!)!)

哇!这意味着如果NSURL(string: urlAdressPhoto)nil,您的程序将崩溃。或者,如果它不是nil,但是对NSData的调用是nil,则您的程序将崩溃。

经验教训是,我不能经常这样说:为方便起见,请不要使用!它会破坏您的代码。虽然偶尔有充分的理由使用它,但大多数人都会使用它,因为它们懒得打开。然后他们得到unexpectedly found nil while unwrapping an Optional value

我冒昧地说这是与Stack Overflow上最常见的Swift相关的问题。每天必须有大约10个与该错误消息相关的问题,这完全是因为人们因为完全超出我的原因而坚持使用!

试试这个:

guard let urlAdressPhoto = (data?[indexPath.item]["picture"])
    , let url = NSURL(string: urlAdressPhoto)
    , let data = NSData(contentsOfURL: url) else { 
        print("Something failed to unwrap..."); return cell
    }

cell.pictureInRowOutlet.image = UImage(data: data)