2016-11-10 119 views
0

我正在使用TODO应用程序,它全部完成并且运行良好,但突然它开始给出错误“致命错误:意外地发现零,同时展开可选值”。需要一些指导!运行时没有错误

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

唯一可选的似乎是“task.name”,你确定这个值不是零吗?您可以尝试在'getdata()'方法或'cellForRow:at:'中添加断点,以确保数据符合您的期望。 – Ollie

回答

1

你应该总是避免展开的,因为如果可选缺少遇到一个运行时错误的危险与!选配。请尝试以下操作:

let taskName = task.name ?? "No name" 
if task.isimportant{ 
    cell.textLabel?.text = " ★ \(taskName)" 
}else{ 
    cell.textLabel?.text = taskName 
}