Can't show the core data in tableview Swift

2019-09-13 05:10发布

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? thanks

标签: ios swift swift3
1条回答
孤傲高冷的网名
2楼-- · 2019-09-13 05:49

Two big mistakes:

  1. You cannot create a cell with the default initializer UITableViewCell() you have to dequeue it.
  2. 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.
<nameOfProperty> is a property in your data model.

查看更多
登录 后发表回答