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

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` 개체는 래핑 해제 시 오류를 보고합니다.

Peter_Zhu

저는 Swift를 배운 적이 없지만 oc의 경험과 오류 메시지를 바탕으로 재사용 풀에 셀이 없고 그렇지 않은 경우에만 재사용 풀에서 셀을 가져오라고 썼다는 대담한 추측을 합니다. 만들어요, 모르겠어요, 그렇죠?

Peter_Zhu

오류 번역: 옵셔널 값을 언팩하면 null 값으로 발견되는데, 이는 어느 정도 널 포인터 문제와 동일합니다.
어떤 값이 초기화되지 않았는지 알 수 있습니다

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿