Luca Contini
Luca Contini

Reputation: 11

CoreData auto-generated swift code error

I'm new to swift and core data. I've created a simple OS X application using core data. So in the AppDelegate.swift there is a lot of auto-generated code. I just want to save name and lastname when I press a button in the MainMenu.xib I've been searching around for a while on how to use core data in a OS X application using swift but with no success. This is my code:

@IBAction func buttonAggiungiNewDipendentePressed(sender : AnyObject) {

        println("Button pressed from popover");

        //var AppDel:AppDelegate = (NSApplication.sharedApplication().delegate as AppDelegate)

        let context = self.managedObjectContext!


        var nome = popAggiungiDipendenteNome.stringValue;
        var cognome = popAggiungiDipendenteCognome.stringValue;

        var newUser = NSEntityDescription.insertNewObjectForEntityForName("Dipendenti", inManagedObjectContext: context) as NSManagedObject

        newUser.setValue(nome, forKey: "nome")
        newUser.setValue(cognome, forKey: "cognome")

        context.save(nil)

        popover.performClose(true);


    }

I'm getting the following crash: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP,subcode=0x0) inside the auto generate code in AppDelegate.swift:

var managedObjectModel: NSManagedObjectModel? {
        // Creates if necessary and returns the managed object model for the application.
        if let mom = _managedObjectModel {
            return mom
        }

       let modelURL = NSBundle.mainBundle().URLForResource("ElencoTelefonicoAkhela2", withExtension: "momd")
        _managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
        return _managedObjectModel!
    }
    var _managedObjectModel: NSManagedObjectModel? = nil

When it tries to return the managedObjectModel. Any idea? Thanx in advance

Upvotes: 1

Views: 813

Answers (1)

user2041042
user2041042

Reputation: 167

instead of insertNewObjectForEntityForName use:

let en = NSEntityDescription.entityForName("Photo", inManagedObjectContext: context)
let photo:Photo = Photo(entity:en, insertIntoManagedObjectContext:context)

Upvotes: 1

Related Questions