ios - 停止 tableView.reloadData() 抛出错误?
问题描述
我正在关注一个简单列表应用程序的教程,您可以在其中通过 UITextField 将项目添加到列表中。但是,它在 tableView.reloadData() 崩溃,我不知道为什么。将 tableView 设为可选会导致它不会崩溃,但也会导致应用程序无法将项目添加到列表中。这是课程代码:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
struct todo {
var text: String
var isDone: Bool
}
var todos = [todo]()
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
todos.append(todo(text: "test", isDone: false))
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return todos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "todo-cell", for: indexPath)
let todo = todos[indexPath.row]
cell.textLabel?.text = todo.text
if todo.isDone {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
var todo = todos[indexPath.row]
todo.isDone = !todo.isDone
todos[indexPath.row] = todo
tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
todos.append(todo(text: textField.text!, isDone: false))
tableView.reloadData() // Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value... crashes here!!
textField.text = ""
textField.resignFirstResponder()
return true
}
}
解决方案
我的第一个猜测是您没有将情节提要中的 tableview 链接到视图控制器。
也许你应该先检查一下。在 viewDidLoad 中放一个断点,看看你的 tableview 是否已经设置好了。如果它为零,那么这就是你的问题。
推荐阅读
- nginx - 如何在 VPS 上部署两个 pyhton/flask 应用程序,重定向到每个应用程序
- jwt - RabbitMQ + OAuth => 用户的 MQTT 登录失败
- github - 如何(或在哪里)构建(或下载)hg19.map 文件
- python - 如何在 SQLAlchemy,Python 中使用 JSON 将更新后的数据和更新前的数据插入到表中?
- html - 内列的大小
- c# - 如何自定义/添加部分到 LiveCharts 图例?
- php - Redis 向键名添加无效字符
- r - 如何在云中的 Jupyter Notebook 中从 R 连接到 DSE/Cassandra?
- c# - GET 请求在浏览器和 Postman 中有效,但在使用 HttpClient 和 RestSharp 时我得到了未经授权
- crystal-reports - 使用水晶报表 sql 表达式作为日期