context?.save(nil) coming up with error

后端 未结 1 1186
盖世英雄少女心
盖世英雄少女心 2021-01-15 07:52

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 valu

相关标签:
1条回答
  • 2021-01-15 08:36

    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 {}
    
    0 讨论(0)
提交回复
热议问题