【发布时间】:2017-11-26 02:22:54
【问题描述】:
我正在从 Core Data 中获取数据,在控制台中打印时返回的数据是正确的。但是 tableview 总是返回空单元格。对象存在,numberOfRowsinSection 也以正确的计数返回。 一直在寻找几个小时,我希望它不是一个错字。任何帮助表示赞赏,代码如下。我尝试了 valueForKey 和 valueForKeypath 都没有成功 谢谢!
import UIKit
import CoreData
class HistoryViewController: UITableViewController{
@IBOutlet var historyTableView: UITableView!
var activitiesHistory: [NSManagedObject] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "Past Workouts"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "historyCell")
let entity = NSEntityDescription.entity(forEntityName: "Activity", in: CoreDataStack.context)
let fetchRequest: NSFetchRequest<Activity> = Activity.fetchRequest()
fetchRequest.entity = entity
//let sortDescriptor = NSSortDescriptor(key: #keyPath(Activity.timestamp), ascending: true)
//fetchRequest.sortDescriptors = [sortDescriptor]
do {
activitiesHistory = try CoreDataStack.context.fetch(fetchRequest)
//print(activitiesHistory)
} catch let error{
//handle error
print(error)
}
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return activitiesHistory.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let workout = activitiesHistory[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "historyCell", for: indexPath)
print(workout.value(forKey: "timestamp"))
cell.textLabel?.text = workout.value(forKey: "timestamp")as? String
//cell.textLabel?.text = "test"
return cell
}
}
【问题讨论】:
-
设置activityHistory后调用tableView.reloadData()
-
谢谢,但单元格还是空的。
-
是否忘记添加委托和数据源?
-
我将委托和数据源设置为那个 ViewController
标签: ios swift core-data tableview