[英]CoreData, displaying saved journeys in a tableview
我试图在表格视图中显示健身式应用程序中记录的所有旅程列表,以显示每个旅程的距离(布尔值)和日期(时间戳)。
目前我刚刚创建了一个变量来包含核心数据文件中的Journeys。 当我打印出journeysArray时,它在控制台中显示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
}
如果Journey
是您的NSManagedObject
子类,则应使用NSFetchedResultsController
来获取持久化对象。
您的SavedJourneysViewController
必须具有对您将用于获取Journey
对象的NSManagedObjectContext
实例的引用。 让我们假设你有一个viewContext
类型的财产NSManagedObjectContext
在SavedJourneysViewController
多数民众赞成被从外面看,无论你初始化设置SavedJourneysViewController
。
你要声明一个fetchedResultsController
在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
}()
然后通过调用try? fetchedResultsController.performFetch()
在viewDidLoad
执行fetch(例如) try? fetchedResultsController.performFetch()
try? fetchedResultsController.performFetch()
:
然后在numberOfRowsInSection
返回fetchedResultsController.sections?[section].objects?.count ?? 0
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
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
}
有关在UITableViewController
使用NSFetchedResultsController
更多信息 -
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.