0

我一直在尝试做一个简单的 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
4

2 回答 2

0

错误是相当微不足道的,这里没有太多要分析的。尝试改变这个:

let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: context)

对此

let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: context)!

与往常一样,新手往往会忽略明显的迹象。该错误清楚地表明 optional 是 type NSEntityDescription。并且鉴于在给定的代码中只实例化了这种类型的对象,因此无需天才就能猜出错误所在。

Value of optional type 'NSEntityDescription?' not unwrapped; did you mean to use '!' or '?'

此外,此处用于实例化 NSEntityDescription 对象的方法声明如下:

class func entityForName(entityName: String, inManagedObjectContext context: NSManagedObjectContext) -> NSEntityDescription? 

...该?字符清楚地告诉我们此方法返回一个可选值。

于 2014-09-13T15:32:39.013 回答
0

我假设Model初始化程序签名是:

init(entity: NSEntityDescription, insertIntoManagedObjectContext: NSManagedObjectContext)

发生编译错误是因为NSEntityDescription.entityForName返回一个可选的,所以你必须解开它。

至于运行时错误,我的猜测是contxtnil,你在这里传递了一个强制解包:

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

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

于 2014-09-13T15:43:04.083 回答