【问题标题】:Displaying correct information in cellForRowAt在 cellForRowAt 中显示正确的信息
【发布时间】:2025-12-24 23:00:12
【问题描述】:

我想我已经接近了,但似乎让自己感到困惑,因为我可以访问所有数据,但无法让它正常运行。

我正在尝试在表格视图中的表格中显示其各自公司(部分)下的员工列表。

关于存储值和关系的我的 CoreData 是正确的。我通过在各个地方使用 print 语句知道这一点。

以下是我的代码,但与cellForRowAt 方法相关的问题的摘要是...

  1. 我可以使用print("Company - \(company.name!) Employee - \(employee.name!)") 打印公司及其员工的列表
    • 公司 - Company1 员工 - Fred Smith
    • 公司 - Company1 员工 - Betty Boo
    • 公司 - Company2 员工 - GI Joe
    • 公司 - Company3 员工 - George Jungle
  2. 如果我设置cell.textLabel?.text = allCompanies[indexPath.section].name,我会在每个部分中获得正确的行数(基于每个公司的employee.count),但它会在每个部分的每一行中显示公司名称
  3. 如果我设置cell.textLabel?.text = employee.name!,我只会在所有行中返回一名员工。所有部门的同一名员工。

CoreData 实体

实体 - 公司
属性 - 名称
关系 - hasEmployee

实体 - 员工
属性 - 名称
关系 - hasCompany

var allCompanies: [Company] = []

func getCompanies() {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Company")
    request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
    request.returnsObjectsAsFaults = false

    do {
        allCompanies = try moc.fetch(request) as! [Company]
    } catch let err {
        print(err)
    }
}

//MARK: - Fetched Results
lazy var fetchedResultsController: NSFetchedResultsController = { () -> NSFetchedResultsController<Employee> in

    let fetchRequest: NSFetchRequest<Employee> = Employee.fetchRequest()
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]

    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
    frc.delegate = self
    return frc
}()

func attemptFetch() {

    do {
        try fetchedResultsController.performFetch()
    } catch let err {
        print(err)
    }
}

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

    let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! EmployeeCell

    for company in allCompanies {
        for employee in company.hasEmployee?.allObjects as! [Employee] {

//                print("Company - \(company.name!)  Employee - \(employee.name!)")
//                cell.textLabel?.text = employee.name!
                cell.textLabel?.text = allCompanies[indexPath.section].name
            }
        }
        return cell
    }

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: swift uitableview core-data


    【解决方案1】:

    如果您想将Company 实例用作部分并将员工用作您可以编写的行

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! EmployeeCell
    
        let company = allCompanies[indexPath.section]
        let allEmployees = company.hasEmployee?.allObjects as! [Employee]
        let employee = allEmployees[indexPath.row]
        cell.textLabel?.text = employee.name
        return cell
     }
    
     func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let company = allCompanies[section]
        return company.name
     }
    

    但我建议使用NSFetchedResultsController 的功能来处理这些部分。

    PS:数组的命名hasEmployees 令人困惑,因为通常前缀hasis 表示Bool。只需将其命名为 employees 并将数组(实际上是一个集合)声明为非可选的。

    【讨论】:

    • vadian,一如既往,你太棒了。谢谢。