首页 文章

在打开可选值时意外地发现了nil

提问于
浏览
-2

以下不起作用 . 以下是应用程序崩溃后它告诉我的内容:

fatal error: unexpectedly found nil while unwrapping an Optional value
class TeacherInputViewController: UIViewController {

    @IBOutlet var textName: UITextField!
    @IBOutlet var textEmail: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func btnSave(sender: AnyObject) {

        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let entity = NSEntityDescription.entityForName("Teachers", inManagedObjectContext: context)          
        let newTeacher = TeacherObject(entity: entity!, insertIntoManagedObjectContext: context)

        newTeacher.name = textName.text
        newTeacher.email = textEmail.text

        context.save(nil)

        println(newTeacher)
        self.navigationController?.popToRootViewControllerAnimated(true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

为什么我在解开可选值时出错?

编辑:这是它说导致问题的一行:让newTeacher = TeacherObject(entity:entity!,insertIntoManagedObjectContext:context)

1 回答

  • 0

    解包的对象必须是 entity! ,因为它是函数调用中唯一的未包装对象 . 因此,您创建变量 entity 的调用最有可能返回nil .

    • 你拼错了实体名称 "Teachers" (看起来很腥:为什么它是复数?),

    • 或您的托管对象上下文是 nil ,在这种情况下,您必须返回到应用程序委托并检查为什么会这样 .

相关问题