2014-09-13 56 views
0

我一直在尝试做一个简单的CoreData任务,保存数据。我确定它可以在Beta 6中运行,但在更新到Beta 7后开始出现错误。Beta 7中的XCode 6 Beta 6错误 - 可选类型的值未解包

我想我必须添加'?'要么 '!'基于错误提示,但只是不够聪明,弄清楚哪里!

@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 

回答

0

错误是fai小小的琐碎,这里没有太多可以分析的地方。尝试改变这一点:

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? 

...的?字符清晰地告诉我们,这个方法返回一个可选。

0

我相信的是,Model初始化签名是:发生

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) 
    } 
} 

并使用调试程序&断点检查是否有任何提到的变量为零。