swift - 我想将 CoreData 中的数据显示到表格视图中
问题描述
我想将 CoreData 中的数据显示到 tableview 中,我正在处理 favouris,我在 favouris 上添加我的事件,我想在 tableview 中显示它,有我的代码:
var lists : [NSManagedObject] = [] {
didSet {
favorisEventTableView.reloadData()
}
}
@IBOutlet weak var favorisEventTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
favorisEventTableView.dataSource = self
favorisEventTableView.delegate = self
loadFavoris()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
favorisEventTableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lists.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = favorisEventTableView.dequeueReusableCell(withIdentifier: "FavorisCell")
let contentView = cell?.viewWithTag(0)
let eventId = contentView?.viewWithTag(4) as! UILabel
let item = lists[indexPath.row]
eventId.text = String((item.value(forKey: "id_event") as! Int))
return cell!
}
func loadFavoris() {
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let coreContext = appDelegate?.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Favoris")
do {
lists = try coreContext!.fetch(fetchRequest)
print(lists)
} catch let error as NSError {
print(error.userInfo)
}
}
但它没有显示任何东西,也许是添加功能的问题?我确定它有效,因为我在控制台上“保存”了,请帮忙?PS:实体“Favoris”只有一个属性“id_event”,它是一个整数
解决方案
你需要在loadFavoris
里面添加viewDidLoad
不cellForRowAt
override func viewDidLoad() {
super.viewDidLoad()
favorisEventTableView.dataSource = self
favorisEventTableView.delegate = self
loadFavoris()
}
推荐阅读
- json - 将String和Int快速存储在字典中
- html - 如何为文本框换行
- html - 我想使用 bootstrap4 在列顶部添加 10 px 边框
- c - 在 C 中运行程序的总线错误
- javascript - 如何使用 optgroup 在选择框中附加 json 数据
- c# - 如何在 wpf C# 中更新网格标题的文本大写样式
- jakarta-mail - GreenMail 集成测试发送的电子邮件未转发给收件人
- php - 在 Laravel 测试期间创建和删除表
- reactjs - 反应输入 onChange 滞后
- ruby-on-rails - 如何进行主动管理员电子邮件搜索以修剪 Rails 应用程序中的先前后续空间