我正在尝试创建一个简单的待办事项列表。在介绍 Realm 或 coreData 之前,我想对其进行测试,看看是否一切顺利。
我知道我可能可以在某些if 条件下完成这项工作,但我希望能够使用nil 合并运算符(我只是喜欢它的简单性),而且我不确定它为什么不起作用。
我让它在没有它的情况下工作,但真的很感兴趣它表现得这样的原因是什么。
当我启动应用程序时,即使我将一些项目添加到数组并打印出来,它也只会显示“未添加类别” ,列表保持不变。
import UIKit
class CategoriesTableView: UITableViewController {
var testData = [FauxData]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
}
// MARK: - Data Methods
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let data = testData[indexPath.row].categoryTitle ?? "No Category Added"
cell.textLabel?.text = data
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testData.count
}
@IBAction func addItem(_ sender: UIBarButtonItem) {
CreateNewItem(item: "test")
tableView.reloadData()
}
func CreateNewItem(item: String) {
let newItem = FauxData()
newItem.categoryTitle = item
testData.append(newItem)
print(item)
}
}
这是 FauxData 类:
class FauxData {
var categoryTitle: String?
}
抱歉,如果这太简单或重复,我无法找到合适的答案。