繁体   English   中英

无法在TableView Swift中显示核心数据

[英]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.
}
}

大家好,我只是尝试在表格视图中显示核心数据,我已经连接了dataSource并将其delegateViewController ,并且我确认核心数据中有一些数据,有人可以帮助我吗? 谢谢

两个大错误:

  1. 您无法使用必须将其出队的默认初始化程序UITableViewCell()创建单元格。
  2. 您必须在数据源数组中获取索引路径的项目,并将属性的值分配给单元格的标签。

     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中指定的标识符。
<nameOfProperty>是数据模型中的一个属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM