2017-09-01 133 views
1

我有EmployeeExampleDeptt为实体。CoreData:关系:保存:查询

  1. EmployeeExample一个与Dept
  2. Dept一个关系与EmployeeExample
  3. 我想通过关系,将数据保存多个关系。我有部门的实体对象,与我要救employeeexample实体

我实现这一点,但我想知道是否是最佳的方式。任何最佳方式?我想知道这种关系是如何工作的。

我的代码:

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: "Deptt", into: context) as! Deptt 
     let emp = NSEntityDescription.insertNewObject(forEntityName: "EmployeeExample", into: (container?.viewContext)!) as! EmployeeExample 
     emp.firstName = "YYYY" 
     emp.lastName = "HHHHHHH" 
     empS.insert(emp) 
     print("Count of Emp SSSS Set == \(empS.count)") 
     let emp1 = NSEntityDescription.insertNewObject(forEntityName: "EmployeeExample", into: (container?.viewContext)!) as! EmployeeExample 
     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 {} 
    } 
} 

难道我每次都要创建一个Employee实例?

回答

1

我一定要每次都创建一个Employee实例?

那么,你有每次新员工?如果你有新的信息,你需要创建一个新的Employee纪录。如果您使用的是现有信息,则可以使用NSFetchRequest从持久存储中查找现有的Employee。当有新的数据要保存时,您可以创建新的实例。无论你需要做的事只有你能回答。如果你有新的数据,是的。否则,不。