Search code examples
core-dataswiftnsmanagedobjectcontext

NSManagedObjectContext does not work in Swift


@IBAction func btnSave(sender: AnyObject) {

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext    
}

This does not work since it says it is not unwrapped.


Solution

  • Because managedObjectContext in application delegate is optional you should unwrap it with an exclamation mark change your code to this:

    let context: NSManagedObjectContext = appDel.managedObjectContext!