微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/swift/320627.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐