我一直在尝试做一个简单的 CoreData 任务,保存数据。我确定它在 Beta 6 中可以工作,但在更新到 Beta 7 后开始出现错误。
我想我必须添加'?或者 '!' 基于错误提示,但不够聪明,无法弄清楚在哪里!
@IBAction func saveItem(sender: AnyObject) {
// Reference to App Delegate
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
// Reference our moc (managed object content)
let contxt: NSManagedObjectContext = appDel.managedObjectContext!
let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: contxt)
// Create instance of our data model and initialize
var newItem = Model(entity: ent, insertIntoManagedObjectContext: contxt)
// Map our attributes
newItem.item = textFieldItem.text
newItem.quanitity = textFieldQuantity.text
newItem.info = textFieldInfo.text
// Save context
contxt.save(nil)
}
错误说
Value of optional type 'NSEntityDescription?' not unwrapped; did you mean to use '!' or '?'
在线上
var newItem = Model(entity: ent, insertIntoManagedObjectContext: contxt)
每次我似乎已经清除错误并编译正常时,单击调试区域中的“保存”显示
fatal error: unexpectedly found nil while unwrapping an Optional value