【发布时间】:2025-12-24 23:00:12
【问题描述】:
我想我已经接近了,但似乎让自己感到困惑,因为我可以访问所有数据,但无法让它正常运行。
我正在尝试在表格视图中的表格中显示其各自公司(部分)下的员工列表。
关于存储值和关系的我的 CoreData 是正确的。我通过在各个地方使用 print 语句知道这一点。
以下是我的代码,但与cellForRowAt 方法相关的问题的摘要是...
- 我可以使用
print("Company - \(company.name!) Employee - \(employee.name!)")打印公司及其员工的列表- 公司 - Company1 员工 - Fred Smith
- 公司 - Company1 员工 - Betty Boo
- 公司 - Company2 员工 - GI Joe
- 公司 - Company3 员工 - George Jungle
- 如果我设置
cell.textLabel?.text = allCompanies[indexPath.section].name,我会在每个部分中获得正确的行数(基于每个公司的employee.count),但它会在每个部分的每一行中显示公司名称 - 如果我设置
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