上下文?.save(nil)出现错误 [英] context?.save(nil) coming up with error
问题描述
如果在上下文中出现以下错误,请使用Xcode 7和swift 2.0?.save(nil)。
Using Xcode 7 and swift 2.0 if get the following error on the context?.save(nil).
感谢任何帮助
不能对'NSManagedObjectContext'类型的非可选值使用可选链接
"cannot use optional chaining on non-optional value of type 'NSManagedObjectContext'
func newItem() {
let context = self.context
let ent = NSEntityDescription.entityForName("CallList", inManagedObjectContext: context)
let nItem = CallList(entity: ent!, insertIntoManagedObjectContext: context)
nItem.firstname = firstName.text
nItem.lastname = lastName.text
nItem.phonenumber = phoneNumber.text
context?.save(nil)
推荐答案
你得到的错误是 context
变量不是可选的,所以?
是没用的。
You get that error as your context
variable is not optional so the ?
is useless.
也是swift 2引入了 do-catch
构造,以允许高级错误处理,就像使用尝试其他语言一样-catch
,所以带有错误参数的函数,例如 save()
的 NSManagedObjectContext
已更改并丢失了错误参数并将错误报告为异常;所以你应该这样做
Also swift 2 introduced the do-catch
construct to allow advanced error handling as you would do in other languages with try-catch
, so functions with an error parameter such as save()
of NSManagedObjectContext
changed and have lost the error parameter and report errors as exceptions; so you should do
do {
try context.save()
} catch let error {
// Handle error stored in *error* here
}
如果你不喜欢我想处理你可以做的错误
If you don't want to handle the error you can do
do {
try context.save()
} catch {}
这篇关于上下文?.save(nil)出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!