gpt4 book ai didi

ios - 核心数据查询返回正确的值,但表格单元格为空

转载 作者:行者123 更新时间:2023-11-30 11:58:44 24 4
gpt4 key购买 nike

我正在从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
}
}

最佳答案

这对我有用。

var activities: [Activity] = []

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
addData()

let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext

do {
activities = try context.fetch(Activity.fetchRequest())
}
catch {

}
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.activities.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = self.activities[indexPath.row].timestamp

return cell
}

Result

关于ios - 核心数据查询返回正确的值,但表格单元格为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47492435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com