【问题标题】:unexpectedly found nil while unwrapping an Optional value - Swift在展开可选值时意外发现 nil - Swift
【发布时间】:2014-10-19 11:06:12
【问题描述】:

我收到此错误:fatal error: unexpectedly found nil while unwrapping an Optional value 在这个函数中:

   func textFieldShouldReturn(textField: UITextField) -> Bool {

    tableViewData.append(textField.text)
    textField.text = ""
    self.tableView.reloadData()
    textField.resignFirstResponder()

    // Reference to our app delegate

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate

    // Reference moc

    let contxt: NSManagedObjectContext = appDel.managedObjectContext!
    let en = NSEntityDescription.entityForName("note", inManagedObjectContext: contxt)

    // Create instance of pur data model an initialize

    var newNote = Model(entity: en!, insertIntoManagedObjectContext: contxt)

    // Map our properties

    newNote.note = textField.text

    // Save our context

    contxt.save(nil)
    println(newNote)

    // navigate back to root vc

    //self.navigationController?.popToRootViewControllerAnimated(true)

    return true
}

还有这行代码:

 var newNote = Model(entity: en!, insertIntoManagedObjectContext: contxt)

有人对此错误有解决方案吗? 我使用 xCode 6.0.1。编程语言为 Swift,模拟器运行 iOS8 (iPhone 5s)。

【问题讨论】:

    标签: core-data swift ios8


    【解决方案1】:

    NSEntityDescription.entityForName("note", inManagedObjectContext: contxt) 返回一个NSEntityDescription?。所以它是可选的,可以是nil。当您强制打开它(使用! 运算符)时,如果它是nil,那么您的程序就会崩溃。为了避免这种情况,您可以使用if-let 语法。方法如下:

    if let entity = NSEntityDescription.entityForName("note", inManagedObjectContext: contxt) {
        // Do your stuff in here with entity. It is not nil.
    }
    

    但是,在核心数据中,实体变为nil 的原因可能是您拼写了名称“note”错误。检查您的 xcdatamodel 文件。

    【讨论】:

    • 感谢您的回答,我的问题是我的名字拼错了。
    【解决方案2】:

    当您打开包含nil 的可选项时会发生该错误。如果那是导致错误的行,那么就是将 en 变量设置为 nil,而您正试图强制解开它。

    我无法提供将其设为nil 的理由,但我建议避免使用强制解包(即使用! 运算符),而是依赖可选绑定:

    if let en = en {
        var newNote = Model(entity: en, insertIntoManagedObjectContext: contxt)
    
        // Map our properties
    
        newNote.note = textField.text
    
        // Save our context
    
        contxt.save(nil)
        println(newNote)
    }
    

    这解决了异常。你应该调查一下为什么ennil

    【讨论】:

      猜你喜欢
      • 2018-09-22
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多