无法在 tableview Swift 中显示核心数据 [英] Can't show the core data in tableview Swift
本文介绍了无法在 tableview Swift 中显示核心数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class showPageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
@IBOutlet weak var tableView: UITableView!
var records : [Record] = []
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return records.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
if editingStyle == .delete{
let record = records[indexPath.row]
context.delete(record)
(UIApplication.shared.delegate as! AppDelegate).saveContext()
do{
records = try context.fetch(Record.fetchRequest())
} catch{
print("Failed")
}
}
}
override func viewWillAppear(_ animated: Bool) {
getData()
tableView.reloadData()
}
func getData(){
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do{
records = try context.fetch(Record.fetchRequest())
} catch{
print("123")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
大家好,我只是尝试在表格视图中显示核心数据,我已经将dataSource
和delegate
连接到ViewController
,我确认核心数据中有一些数据,任何人都可以帮助我吗?谢谢
Hello everyone, I just tried to show the core data in table view, I already connect the dataSource
and delegate
to the ViewController
, and I confirmed There are some data in core data, anyone can help me plz? thanks
推荐答案
两个大错误:
- 您不能使用默认初始化程序
UITableViewCell()
创建单元格,您必须将其出列. 您必须获取索引路径的数据源数组中的项目,并将属性值分配给单元格的标签.
- You cannot create a cell with the default initializer
UITableViewCell()
you have to dequeue it. You have to get the item in the data source array for the index path and assign a value of a property to a label of the cell.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let record = records[indexPath.row]
cell.textLabel!.text = record.<nameOfProperty>
return cell
}
cell
是 Interface Builder 中指定的标识符.
是数据模型中的一个属性.
cell
is the identifier specified in Interface Builder.
<nameOfProperty>
is a property in your data model.
这篇关于无法在 tableview Swift 中显示核心数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文