ios - 不会处理从这里抛出的错误,因为 context.save 中的封闭捕获并不详尽

标签 ios swift core-data try-catch xcode8

我在将 xcode 更新到版本 8.3.2 后遇到问题并尝试。该代码可以工作,但更新后就不再工作了。它符合以下代码:

func saveContext() -> NSError?{// It saving
        do {
            if  context == context {
                try context.save()
           // taskNameTextField.text=nil
            }
        } catch let error as! NSError? {
            print("error saving core data: \(error)")
            return error
        }
        return nil
    } //

有人可以帮助我吗?

最佳答案

事实证明,从 Swift 2 更新到 Swift 3 时,Apple 转换器并不能捕获代码中的所有问题。您需要自己更新一些内容。它没有捕获的事情之一是所有对 NSError 的引用。它遗漏了几个需要将 NSError 转换为 Error 的地方。

func saveContext() -> Error?{ // remove the `NS` from Error here.
    do {
        if  context == context { // this is always true, remove it.
            try context.save()
        }
    } catch { // remove the `let error as! NSError?` from here
        print("error saving core data: \(error)")
        return error
    }
    return nil
}

该函数的简单版本是:

func saveContext() -> Error? {
    do {
        try context.save()
        return nil
    } catch {
        return error
    }
}

或者实现上一级的catch,它会变成:

func saveContext() throws {
    try context.save()
}

关于ios - 不会处理从这里抛出的错误,因为 context.save 中的封闭捕获并不详尽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44056294/

相关文章:

ios - 通过 Storyboard删除 UITableViewCell 中内容 View 的填充

ios - 在 iOS 中重用样式

swift - 如何使用网格线之间的最小值、最大值和固定步长设置 iOS 图表 y 轴?

swift - 核心数据性能问题

iphone - NSFetchedResultsController 索引超出范围

ios - CocoaPods 因错误停止安装 Firebase/Analytics

ios - 如何检查用户字典中的键是否更改?

cocoa - 核心数据实体中可本地化属性值的模型?

ios - Swift:如何在屏幕边框上制作标签?

ios - Swift 调用 IBAction 方法不起作用