Core data NSManagedObjectContext在Swift中不起作用

Core data NSManagedObjectContext在Swift中不起作用,core-data,swift,nsmanagedobjectcontext,Core Data,Swift,Nsmanagedobjectcontext,这不起作用,因为它表示它未展开。因为应用程序委托中的managedObjectContext是可选的。您应该使用感叹号将其展开。请将代码更改为: @IBAction func btnSave(sender: AnyObject) { let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate let context: NSManagedObjectContext = ap

这不起作用,因为它表示它未展开。

因为应用程序委托中的
managedObjectContext
是可选的。您应该使用感叹号将其展开。请将代码更改为:

@IBAction func btnSave(sender: AnyObject) {

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

您需要打开它,然后使用类似这样的if语句以安全的方式继续

let context: NSManagedObjectContext = appDel.managedObjectContext!

您是否在AppDelegate madelURL中进行了更改

@IBAction func btnSave(sender: AnyObject) {
    if let context:NSManagedObjectContext = appDel.managedObjectContext! as NSManagedObjectContext {
        // safe to use the context here
    }    
}

致命错误:在展开可选值时意外发现nil。这不是Xcode问题。
lazy var managedObjectModel: NSManagedObjectModel = {
    let modelURL = NSBundle.mainBundle().URLForResource("**YOURPROJECTNAME**", withExtension: "momd")!
    return NSManagedObjectModel(contentsOfURL: modelURL)!
}()