2014-10-19 42 views
0

我得到這個錯誤: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)運行。

回答

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也許是你拼寫的名字「注意」錯誤。檢查你的xcdatamodel文件。

+0

感謝您的回答,我的問題是我拼寫不好的名字。 – 2016-08-09 08:40:48

0

當您打開包含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雖然。

相關問題