未解包的可选类型NSManagedObjectContext的值

时间:2014-09-20 10:27:56

标签: swift

@IBAction func start(sender: UIButton)
{
    var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as    AppDelegate)
    var context: NSManagedObjectContext = appDel.managedObjectContext

    var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
    newUser.setValue(label!.text, forKey: "score")

    context.save(nil)

    startGame()
    startButton!.enabled = (startButton!.titleLabel!.text == "Start")
}

当我使用NSManagedObjectContext时,它说我需要打开该值,但是当我这样做时,会弹出一个致命的错误,"在打开一个可选值"时找到nil。我没有将NSManagedObjectContext设置为可选类型。谁能帮我?感谢。

1 个答案:

答案 0 :(得分:0)

在我看来,您应该遵循最新的Apple Xcode模板并使用可选的:

lazy var managedObjectContext: NSManagedObjectContext? = {
   let coordinator = self.persistentStoreCoordinator
   if coordinator == nil {
       return nil
   }
   var managedObjectContext = NSManagedObjectContext()
   managedObjectContext.persistentStoreCoordinator = coordinator
   return managedObjectContext
}()

let context = appDelegate.managedObjectContext!