Swift 2迁移在AppDelegate中的saveContext()

我刚刚下载了新的Xcode 7.0测试版,并从Swift 1.2迁移到Swift 2.迁移显然没有改变整个代码,实际上是一个方法saveContext(),直到抛出2个错误为止:
if moc.hasChanges && !moc.save() {

Binary operator ‘&&’ cannot be applied to two Bool operands

Call can throw,but it is not marked with ‘try’ and the error is not handled

方法如下所示:

// MARK: - Core Data Saving support
func saveContext () {
    if let moc = self.managedobjectContext {
        var error: NSError? = nil
        if moc.hasChanges && !moc.save() {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application,although it may be useful during development.
            NSLog("Unresolved error \(error),\(error!.userInfo)")
            abort()
        }
    }
}

任何想法如何让它工作?

您提供的两个错误中的第一个是误导,但第二个是现成的。问题在!moc.save()中,从Swift 2开始,不再返回Bool,而是注释的throws。这意味着您必须尝试此方法并捕获可能发出的任何异常,而不是仅检查其返回值为true或false。

为了反映这一点,在Xcode 7中使用Core Data创建的一个新项目将生成以下样板代码,可以替代您使用的代码

func saveContext () {
    if managedobjectContext.hasChanges {
        do {
            try managedobjectContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application,although it may be useful during development.
            let nserror = error as NSError
            NSLog("Unresolved error \(nserror),\(nserror.userInfo)")
            abort()
        }
    }
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...