2016-11-10 118 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 
}