首页 > 解决方案 > CoreData,在表格视图中显示保存的旅程

问题描述

我正在尝试在表格视图中显示健身风格应用程序中记录的所有旅程的列表,以显示每次旅程的距离(布尔值)和日期(时间戳)。

目前我刚刚创建了一个变量来包含核心数据文件中的旅程。当我打印出旅程数组时,即使有一些记录的旅程,它也会在控制台中显示 0。

import UIKit
import CoreData

class SavedJourneysViewController: UITableViewController {

    var journeyArray: [Journey] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print(journeyArray.count)
        return journeyArray.count

    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "JourneyItem", for: indexPath)
        return cell

    }

标签: iosswiftcore-data

解决方案


如果Journey是你的NSManagedObject子类,你应该使用 aNSFetchedResultsController来获取持久化的对象。

SavedJourneysViewController必须具有对NSManagedObjectContext用于获取Journey对象的实例的引用。让我们假设您的viewContexttype 属性是从外部设置的,无论您在何处初始化.NSManagedObjectContextSavedJourneysViewControllerSavedJourneysViewController

您需要声明一个fetchedResultsControllerin SavedJourneysViewController

private lazy var fetchedResultsController: NSFetchedResultsController<Journey> = {
    let fetchRequest: NSFetchRequest< Journey > = Journey.fetchRequest()
    let sortDescriptor = NSSortDescriptor(keyPath: \Journey.date, ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]
    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: viewContext, sectionNameKeyPath: nil, cacheName: nil)
    return fetchedResultsController
}()

然后viewDidLoad通过调用(例如)执行获取try? fetchedResultsController.performFetch()

然后作为numberOfRowsInSection回报fetchedResultsController.sections?[section].objects?.count ?? 0

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return fetchedResultsController.sections?[section].objects?.count ?? 0
}

不要忘记实施func numberOfSections(in tableView: UITableView) -> Int和返回fetchedResultsController.sections?.count ?? 0

func numberOfSections(in tableView: UITableView) -> Int {
    return fetchedResultsController.sections?.count ?? 0
}

cellForRowAt中,使用对象配置您的单元格Journey

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = let cell = tableView.dequeueReusableCell(withIdentifier: "JourneyItem", for: indexPath)
    guard let journey = fetchedResultsController.sections?[indexPath.section].objects?[indexPath.row] as? Journey else {
        return cell
    }
    // handle cell configuration
    cell.textLabel?.text = String(journey.distance)
    return cell
}

更多关于NSFetchedResultsController使用UITableViewController-


推荐阅读