1
votes

I have following database,

enter image description here

I have following NSManagedObject class for Employee.

import Foundation import CoreData

class Employee: NSManagedObject {

    @NSManaged var age: NSNumber
    @NSManaged var firstName: String
    @NSManaged var gender: String
    @NSManaged var lastName: String
    @NSManaged var salary: NSNumber

}

I have on UIViewController class which contains 5 UITextFields and one UIButton to adding values in Database.

If I insertValue in same class, like

let employee:Employee = NSEntityDescription.insertNewObjectForEntityForName("Employee", inManagedObjectContext: self.managedObjectContext!) as Employee

It works fine, but I followed Object Oriented Structure of App and made a DatabaseManager.swift Class,

so now issue I am facing is to pass NSManagedObject from Controller class to DatabaseManager class.

I coded as follows, but its giving error.

@IBAction func addToDatabase(sender: UIButton) {
    println("Add to Database is clicked")

    var employee:Employee = Employee() //Employee is subclass of NSManagedObject

    employee.firstName = textfield_firstName.text
    employee.lastName = textfield_lastName.text
    employee.gender = textfield_gender.text
    employee.age = (textfield_age.text as String).toInt()!
    employee.salary = (textfield_salary.text as String).toInt()!

    var databaseManager:DatabaseManager = DatabaseManager()
    databaseManager.saveEmployee(employee)

}

ERROR:

2014-11-06 10:34:46.710 CoreDataWithSwift[588:9220] CoreData: error: Failed to call designated initializer on NSManagedObject class 'CoreDataWithSwift.Employee' 
2014-11-06 10:34:46.736 CoreDataWithSwift[588:9220] -[CoreDataWithSwift.Employee setFirstName:]: unrecognized selector sent to instance 0x7fa269e20800
2014-11-06 10:34:46.756 CoreDataWithSwift[588:9220] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CoreDataWithSwift.Employee setFirstName:]: unrecognized selector sent to instance 0x7fa269e20800'

Thanks.

1
See stackoverflow.com/a/23835907/1187415. That's for Objective-C, but the underlying problem is the same. - Martin R

1 Answers

2
votes

You are not supposed to created NSManagedObject instances directly, but instead call:

var employee = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: managedObjectContext) as Employee?

and then change employee's properties and save the result.