【问题标题】:Core data query returns correct values but table cell is empty核心数据查询返回正确值但表格单元格为空
【发布时间】: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


【解决方案1】:

这对我有用。

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

【讨论】:

  • 谢谢!但问题有所不同,因为我在数据模型中使用了 DATE 类型。解决方案发布在下面。
【解决方案2】:

感谢您的所有帮助!我找到了解决方案:

问题是从数据库返回的数据类型为“日期”。单元格只会显示空白,Xcode 会显示警告或错误。当我使用 DateFormatter() 将类型转换为格式化字符串时,单元格显示了数据。代码如下:

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let workout = activities[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "historyCell", for: indexPath)
    let time = workout.value(forKey: "timestamp")
    let formatter = DateFormatter()
    formatter.dateFormat = "dd-MM"
    let formatteddate = formatter.string(from: time as! Date)
    cell.textLabel?.text = formatteddate
    return cell
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多