首页 > 解决方案 > 我想将 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”,它是一个整数

标签: swiftcore-data

解决方案


你需要在loadFavoris里面添加viewDidLoadcellForRowAt

override func viewDidLoad() {
      super.viewDidLoad()
      favorisEventTableView.dataSource = self
      favorisEventTableView.delegate = self
      loadFavoris()
}

推荐阅读