核心数据 - 关系

时间:2017-08-31 20:12:22

标签: core-data save

请告诉我如何通过关系保存对象。 如果我有两个实体,如Notes,Category实体 注意是类别的一对一。 类别多对一为Notes。

如果我们有Notes的类别上下文,如何保存..

请提供一些意见。

如何通过套装保存。这将是非常好的

我有员工和部门实体。部门与员工有一对多的关系。员工与部门有一对一的关系。我希望使用部门实体保存员工实体的对象。

每次我为员工创建新的对象 -

import UIKit
import CoreData
class ViewController: UIViewController {

    var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    var empSet = NSSet()
    var empS = Set<EmployeeExample>()
    override func viewDidLoad() {
        super.viewDidLoad()
        var context:NSManagedObjectContext = (container?.viewContext)!
        let dept = NSEntityDescription.insertNewObject(forEntityName: "Department", into: context) as! Department
        let emp = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: (container?.viewContext)!) as! Employee
        emp.firstName = "YYYY"
        emp.lastName = "HHHHHHH"
        empS.insert(emp)
        print("Count of Emp SSSS Set == \(empS.count)")
        let emp1 = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: (container?.viewContext)!) as! Employee
        emp1.firstName = "RRRRR"
        emp1.lastName = "YYYYY"
        empS.insert(emp1)
        empSet.addingObjects(from: empS)
        dept.deptName = "CCC"
        print("Count of Emp SSSS Set == \(empS.count)")
        print("Count of Emp Set == \(empSet.count)")
        dept.addToEmp(empSet)
        do {
            try appDelegate.saveContext()
            print("Saved -------------")
        }catch {
            print("Error")
        }
    }



}

1 个答案:

答案 0 :(得分:1)

  

我对这些行有疑问anEmployee.department = newDepartment如何获取newDepartment值。我是否必须声明让newDepartment = NSEntityDescription.insertNewObject(forEntityName:“Department”,进入:( container?.viewContext)!)as!系。

此处的Employee对象是与该特定Department对象相关的任何对象。你如何得到它取决于你的应用程序如何工作,但你可能想要做其中之一:

  1. 如果员工属于您应用中尚不存在的新部门,则可以创建anEmployee.department的新实例,并将该对象指定为Department
  2. 如果员工属于您应用中已存在的部门,则使用已存在的Department。您可以通过从{1}}或使用NSFetchRequest从核心数据中获取NSFetchedResultsController个对象来实现此目的。
相关问题