我正在开发TODO应用程序,它已全部完成且运行良好但突然开始出现错误“致命错误:在打开可选值时意外发现nil”。需要一些指南!
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var tableView: UITableView!
var tasks : [Task] = [ ]
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
getdata()
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let task = tasks[indexPath.row]
if task.isimportant{
cell.textLabel?.text = " ★ \(task.name!)"
}else{
cell.textLabel?.text = task.name!
}
return cell
}
func getdata() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do{
tasks = try context.fetch(Task.fetchRequest())
}
catch {
print ("Failed!")
}
}
}
答案 0 :(得分:1)
您应始终避免使用!
展开选项,因为如果缺少可选项,可能会遇到运行时错误。请尝试以下方法:
let taskName = task.name ?? "No name"
if task.isimportant{
cell.textLabel?.text = " ★ \(taskName)"
}else{
cell.textLabel?.text = taskName
}