ios - unexpectedly found nil while unwrapping an Optional value?
PHPz
PHPz 2017-04-17 17:36:59
0
3
526

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)

PHPz
PHPz

学习是最好的投资!

全部回覆(3)
巴扎黑

物件restaurant没有初始化,而且后来tableView:cellForRowAtIndexPath使用restaurant对象时它也没有值,一个null`物件在 unwrap 的時候會報錯。

Peter_Zhu

swift我沒有學過,不過根據 oc 的經驗和錯誤訊息大膽猜測,你只寫了從重用池裡取cell,如果重用池裡沒有,而你沒有創建,不知道對不?

Peter_Zhu

錯誤翻譯:optional值拆包的時候發現是空值,在某種程度相當於是空指標的問題
可以找一下哪些值沒有初始化

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!