我已在两个实体中插入数据。使用以下方法:
func addEmployees() {
let companyEntity = NSEntityDescription.entityForName("Company", inManagedObjectContext: managedContext)
let company = Company(entity: companyEntity!, insertIntoManagedObjectContext: managedContext)
company.name = txtCompany.text
let employeesEntity = NSEntityDescription.entityForName("Employees", inManagedObjectContext: managedContext)
let employees = Employees(entity: employeesEntity!, insertIntoManagedObjectContext: managedContext)
employees.name = txtName.text
employees.empAge = Int(txtAge.text!)
employees.address = txtAddress.text
// employees.company = company
company.mutableSetValueForKey(EntityName().employee).addObject(employees)
do {
try managedContext.save()
} catch {
fatalError("Error in saving Data...")
}
}
并使用此方法检索数据:
func fetchCompanyName() {
let request = NSFetchRequest(entityName: EntityName().company)
if managedContext.countForFetchRequest(request, error: nil) > 0 {
do {
let fetchResult = try managedContext.executeFetchRequest(request)
company = fetchResult as! [Company]
} catch {
fatalError("Error in fetching company")
}
}
}
我想在部分标题和单元格中的员工列表中显示公司名称。部分的数量将等于公司名称。我不知道怎么做???
感谢您的帮助
答案 0 :(得分:0)
您可以简单地为您的公司提取获取请求,然后通过其关系访问您的员工。
// Create a fetch Request for all companies.
let request = NSFetchRequest(entityName: EntityName().company)
// Retrieve an array of companies.
let companies = try! managedContext.executeFetchRequest(request) as! [Company]
// Ex: Get the employees for the first company.
let firstCompanyEmployees = companies[0].employees
现在您已将所有公司都放入数组中,您只需使用您的UITableView
和每个company.name
内容填充UITableViewCell
标题,并附上员工信息。
请记住,您必须遵守UITableViewDataSource
协议,以提供必要的信息,例如:每个部分的title和细胞的content。
希望有所帮助:)