user7529768
user7529768

Reputation: 21

CoreData:Relationship:Save:Query

I have EmployeeExample and Deptt as entities.

  1. EmployeeExample one to one relationship with Dept
  2. Dept has more than one relationship with EmployeeExample
  3. I want to save data through relationship. I have dept entity object, with that I want to save employeeexample entity

I achieved this, but I want to know whether it is the optimal way. Any optimal way? I would like to know how the relationship works.

My code :

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 {}
    }
}

Do I have to create an Employee instance each time?

Upvotes: 1

Views: 62

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70936

Do I have to create an Employee instance each time?

Well, do you have a new employee each time? If you have new information, you need to create a new Employee record. If you're using existing information, you look up an existing Employee from your persistent store by using NSFetchRequest. You create new instances when you have new data to save. Whether you need to do that is something only you can answer. If you have new data, yes. Otherwise, no.

Upvotes: 1

Related Questions