[英]Can't show the core data in 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.
}
}
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? 大家好,我只是尝试在表格视图中显示核心数据,我已经连接了dataSource
并将其delegate
给ViewController
,并且我确认核心数据中有一些数据,有人可以帮助我吗? thanks 谢谢
Two big mistakes: 两个大错误:
UITableViewCell()
you have to dequeue it. 您无法使用必须将其出队的默认初始化程序UITableViewCell()
创建单元格。 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
is the identifier specified in Interface Builder. cell
是在Interface Builder中指定的标识符。
<nameOfProperty>
is a property in your data model. <nameOfProperty>
是数据模型中的一个属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.