我必须进入实体并且两者都已连接。
我想在公司实体值中插入值,但我不知道如何在company.employees(NSSet)中插入值。
员工和公司课程如下:
extension Employees {
@NSManaged var name: String?
@NSManaged var age: NSNumber?
@NSManaged var address: String?
@NSManaged var company: Company?
}
extension Company {
@NSManaged var name: String?
@NSManaged var employees: NSSet?
}
// here i want to insert value
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.age = Int(txtAge.text!)
employees.address = txtAddress.text
// getting no idea here how to save values to NSSet??
// company.employees =
do {
try managedContext.save()
} catch {
fatalError("Error in saving Data...")
}
}
答案 0 :(得分:6)
从另一端做起来总是比较容易:
employees.company = company
核心数据将处理关系的多个方面,因为您已在数据模型中指定了反向关系。
此外,重命名您的实体。它应该被称为Employee
,因为每个实体代表一个雇员。它将为您节省大量的混乱。
如果你真的坚持从公司端编辑它,你就这样做:
company.mutableSetValueForKey("employees").addObject(employees)
我希望你会同意这一点非常丑陋且更容易出错。