Core data Beta 7中的XCode 6 Beta 6错误-可选类型的值未展开
我一直在尝试一个简单的CoreData任务,即保存数据。我确信它在Beta 6中可以工作,但在升级到Beta 7后,错误开始出现 我想我必须加上“?”或“!”基于错误提示,但只是不够聪明,无法找出错误所在Core data Beta 7中的XCode 6 Beta 6错误-可选类型的值未展开,core-data,swift,xcode6,xcode6-beta7,Core Data,Swift,Xcode6,Xcode6 Beta7,我一直在尝试一个简单的CoreData任务,即保存数据。我确信它在Beta 6中可以工作,但在升级到Beta 7后,错误开始出现 我想我必须加上“?”或“!”基于错误提示,但只是不够聪明,无法找出错误所在 @IBAction func saveItem(sender: AnyObject) { // Reference to App Delegate let appDel: AppDelegate = UIApplication.sharedApplication()
@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)
每次我似乎已清除错误并编译ok,单击调试区域中的“保存”显示
fatal error: unexpectedly found nil while unwrapping an Optional value
这个错误很小,这里没有太多要分析的。尝试更改此选项:
let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: context)
对此
let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: context)!
和往常一样,新手往往忽视了告密信号。该错误明确说明可选的类型为NSEntityDescription。鉴于在给定的代码中只实例化了这种类型的对象,不需要天才就能猜出错误所在
Value of optional type 'NSEntityDescription?' not unwrapped; did you mean to use '!' or '?'
此外,此处用于实例化NSEntityDescription对象的方法声明如下:
class func entityForName(entityName: String, inManagedObjectContext context: NSManagedObjectContext) -> NSEntityDescription?
。。。这个字符清楚地告诉我们此方法返回可选的。我假定模型初始值设定项签名为:
init(entity: NSEntityDescription, insertIntoManagedObjectContext: NSManagedObjectContext)
之所以发生编译错误,是因为NSEntityDescription.entityForName返回可选值,因此必须将其展开
至于运行时错误,我猜contxt为零,您在这里传递的是一个强制展开:
let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: contxt)
为了使代码更安全、更清晰,我会明确使用选项:
let contxt: NSManagedObjectContext? = appDel.managedObjectContext
if let contxt = contxt {
let ent: NSEntityDescription? = NSEntityDescription.entityForName("List", inManagedObjectContext: contxt)
// Create instance of our data model and initialize
if let ent = ent {
var newItem = Model(entity: ent, insertIntoManagedObjectContext: contxt)
}
}
并使用调试器和断点检查上述变量是否为nil