为什么我的获取请求导致错误致命错误:在展开Optional值时意外发现nil?

时间:2016-05-02 14:18:47

标签: ios swift core-data nsmanagedobjectcontext nsfetchrequest

下面是我的一个名为post的按钮的代码。这基本上从我的文本字段和文本视图中获取信息,并将其保存到我的核心数据管理对象上下文中。然后,我希望通过获取请求检索此信息,并收到上述错误。我在这里做错了什么想法?

 @IBAction func post(sender: AnyObject) {

    var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    var context: NSManagedObjectContext = appDel.managedObjectContext

    let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName("Entity", inManagedObjectContext: context) as NSManagedObject

    // If appropriate, configure the new managed object.
    // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
    newManagedObject.setValue(NSDate(), forKey: "timeStamp")


    if titleField.text != nil {
       newManagedObject.setValue(titleField.text, forKey: "title")
    }
    if bodyField.text != nil {
       newManagedObject.setValue(bodyField.text, forKey: "body")
    }

    var request = NSFetchRequest(entityName: "Entity")

    request.returnsObjectsAsFaults = false

    do {
        try context.save()

        let results = try context.executeFetchRequest(request)

        print(context)

        print(results)
    } catch {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        //print("Unresolved error \(error), \(error.userInfo)")
        abort()
    }

}

0 个答案:

没有答案