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