context?.save(nil) coming up with error

2019-02-19 17:02发布

Using Xcode 7 and swift 2.0 if get the following error on the context?.save(nil).

Any help is appreciated

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

1条回答
我只想做你的唯一
2楼-- · 2019-02-19 17:34

You get that error as your context variable is not optional so the ? is useless.

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 {}
查看更多
登录 后发表回答