search

Home  >  Q&A  >  body text

ios - unexpectedly found nil while unwrapping an Optional value?

import UIKit

class DetailTableViewController: UITableViewController {

var restaurant: Restaurant!

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    imageView.image = UIImage(named: restaurant.image)

}

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

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 4
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCellWithIdentifier("DetailCell", forIndexPath: indexPath) as! DetailTableViewCell
    
    switch indexPath.row{
    case 0:
        cell.fieldLabel.text = "Restaurant Name"
        cell.valueLabel.text = restaurant.name
    case 1:
        cell.fieldLabel.text = "Restaurant Type"
        cell.valueLabel.text = restaurant.type
    case 2:
        cell.fieldLabel.text = "Restaurant Location"
        cell.fieldLabel.text = restaurant.location
    case 3:
        cell.fieldLabel.text = "Visted?"
        cell.fieldLabel.text = restaurant.isVisted ? "Yes":"No"
    default:
        cell.fieldLabel.text = ""
        cell.valueLabel.text = "" 
    }
    return cell
}

}

错误信息: fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

PHPzPHPz2887 days ago605

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 17:38:59

    Objectrestaurant没有初始化,而且后来tableView:cellForRowAtIndexPath使用restaurant对象时它也没有值,一个null`Object will report an error when unwrap.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 17:38:59

    I have never learned Swift, but based on the experience of oc and the error message, I make a bold guess that you only wrote to get the cell from the reuse pool. If there is no cell in the reuse pool and you have not created it, I don’t know, is that right?

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 17:38:59

    Error translation: When the optional value is unpacked, it is found to be a null value, which is equivalent to a null pointer problem to some extent.
    You can find which values ​​​​have not been initialized

    reply
    0
  • Cancelreply