S. Bharti S. Bharti - 2 years ago 206
Swift Question

How to save value in NSSet Core Data (Swift)

I have to Entity in and both are connected.

enter image description here

I want to insert value in Company entity value but i have no idea how to insert value in company.employees(NSSet).

Both Employees and Company classes are given below:

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...")


Answer Source

It's always easier to do it from the other end:

employees.company = company

Core data will take care of the many side of the relationship because you've specified the inverse relationship in your data model.

Also, rename your entity. It should be called Employee, since each entity represents one employee. It will save you a lot of confusion down the road.

If you really insist on editing it from the company end, you do it like this:


Which I hope you'll agree is significantly uglier and more prone to errors.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download