我正在关注一些过时的youtube教程,并且已经在这个问题上停留了3天了。我正在制作一个简单的待办事项应用程序。我想在tableView中显示数据库中所有任务的名称。
数据库结构如下:
-Task
-unique task ID
-description
-name
所以我试图获取数据库中所有任务的名称,并将它们显示在tableView中。
这就是我所拥有的:
ref = FIRDatabase.database().reference()
var tasks: [Task] = []
ref.child("Task").queryOrderedByKey().observe(.childAdded, with: { snapshot in
let snapshotValue = snapshot.value as? NSDictionary
let taskName = snapshotValue?["name"] as? String
let taskDescrip = snapshotValue?["description"] as? String
let addTask = Task()
addTask.descrip = taskDescrip!
addTask.name = taskName!
self.tasks.append(addTask)
self.tableView.reloadData()
})
所有内容都按预期打印,但是当我添加代码以在tableView单元格中呈现名称时,应用程序每次都会崩溃并打印
"致命错误:指数超出范围"
关于tasks[indexPath.row]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tasks.count == 0 {
return 1
}
return tasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
if tasks.count == 0 {
cell.textLabel?.text = "No tasks"
}
let thisTask = tasks[indexPath.row]
cell.textLabel?.text = thisTask.name
return cell
}
答案 0 :(得分:2)
您需要将git cherry-pick <commit-id>
和let thisTask = tasks[indexPath.row]
放在cell.textLabel?.text = thisTask.name
条件的else
块内,因为您的数组是空的并且它正在尝试从中访问第一个对象。所以它应该是这样的。
if
注意:在Swift中使用原生if tasks.count == 0 {
cell.textLabel?.text = "No tasks"
}
else {
let thisTask = tasks[indexPath.row]
cell.textLabel?.text = thisTask.name
}
return cell
和Dictionary
代替Array
和NSDictionary
。
答案 1 :(得分:1)
在方法“func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath)”中添加代码“
... if tasks.count == 0 { cell.textLabel?.text =“没有任务” 返回细胞 }
.... 返回细胞 }