【发布时间】:2017-07-29 06:28:11
【问题描述】:
我在控制台中收到以下错误:
致命错误:在展开可选值时意外发现 nil
并在 Xcode 编辑器中显示如下错误:
线程 1 EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0*0)
我在 Swift 3 中有这段代码用于调用 API 并将其加载到视图中:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.nameLabel!.text = nameArray[indexPath.row]
cell.dobLabel!.text = dobArray[indexPath.row]
cell.descLabel!.text = descArray[indexPath.row]
/*
let imgURL = NSURL(string: imgURLArray[indexPath.row])
let data = NSData(contentsOf: (imgURLArray as? URL)!)
cell.imageView!.image = UIImage(data: data as! Data)
*/
return cell
}
这是我的 TableViewCell 文件:
class TableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel?
@IBOutlet weak var descLabel: UILabel?
@IBOutlet weak var dobLabel: UILabel?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
【问题讨论】:
-
为什么要用cell.nameLabel!作为可选?你能分享自定义单元格文件吗?
-
您是否创建了自定义 Cell 类?
-
您使用
!强制取消引用您的选项,但如果嵌入了 nil,那么您取消引用 nil 指针。如果您觉得使用?和 optional 是第一条基本规则,那么您更喜欢使用它。 -
在哪一行?请不要让人们猜测,您是在寻求帮助,因此您有责任提供所有必要的信息。你检查了什么答案???
-
天哪,不要使用 4 个单独的数组来存储 4 条相关数据的集合。制作一个包含 4 条数据的结构或对象,并且只有这些结构/对象的一个简单数组