-2
@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.

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
Henry OM
  • 83
  • 7

3 Answers3

0

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!
Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
0

You need to unwrap it, and then continue in a safe way with an if statement like so.

@IBAction func btnSave(sender: AnyObject) {
    if let context:NSManagedObjectContext = appDel.managedObjectContext! as NSManagedObjectContext {
        // safe to use the context here
    }    
}
skymook
  • 3,401
  • 35
  • 39
0

Did you change in AppDelegate madelURL ?

lazy var managedObjectModel: NSManagedObjectModel = {
    let modelURL = NSBundle.mainBundle().URLForResource("**YOURPROJECTNAME**", withExtension: "momd")!
    return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
oscarr
  • 529
  • 5
  • 6