在appDelegate中进行Swift 2迁移saveContext() [英] Swift 2 migration saveContext() in appDelegate

查看:86
本文介绍了在appDelegate中进行Swift 2迁移saveContext()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚下载了新的Xcode 7.0 beta,并完成了从Swift 1.2到Swift 2的迁移.迁移显然并没有改变整个代码,实际上,方法saveContext()很好,直到该行抛出2个错误为止:

I have just downloaded the new Xcode 7.0 beta and did a migration from Swift 1.2 to Swift 2. The migration apparently did not change the whole code, in fact a method saveContext() which was fine until throws 2 errors for the line:

if moc.hasChanges && !moc.save() {

二进制运算符&&"不能应用于两个布尔操作数

Binary operator '&&' cannot be applied to two Bool operands

呼叫可以抛出,但未标记为"try",并且未处理错误

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()
        }
    }
}

关于如何使其工作的任何想法?

Any ideas on how to get it working?

推荐答案

您提供的两个错误中的第一个是令人误解的,但第二个是正确的.问题出在!moc.save()中,从Swift 2开始,它不再返回Bool,而是被注释为throws.这意味着您必须try此方法和catch它可能发出的任何异常,而不仅仅是检查其返回值是true还是false.

The first of the two errors you provided is misleading, but the second is spot on. The problem is in !moc.save() which as of Swift 2, no longer returns Bool and is instead annotated throws. This means that you you have to try this method and catch any exceptions that it may emit, instead of just checking wether its return value is true or false.

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

To reflect this, a new project created in Xcode 7 using Core Data will produce the following boilerplate code which can replace the code you're using.

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()
        }
    }
}

这篇关于在appDelegate中进行Swift 2迁移saveContext()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆