【问题标题】:Nil while unwrapping an Optional value but, during print the value existNil 在展开可选值时,但在打印期间存在该值
【发布时间】:2016-04-16 04:08:22
【问题描述】:

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

类 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

}

谁能告诉我为什么以及如何解决这个问题?

【问题讨论】:

  • NSData(contentsOfURL: NSURL(string: urlAdressPhoto)!)! 您强制解开两个选项 - 这会导致崩溃。修复它。
  • 但是当我在任何情况下尝试删除! 时,Xcode 都会收到错误提示
  • 阅读可选项以及如何有条件地打开它们。

标签: ios swift uiimage tableview nsurl


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多