Swift 2迁移在AppDelegate中的saveContext()
发布时间:2020-12-14 05:56:24 所属栏目:百科 来源:网络整理
导读:我刚刚下载了新的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
我刚刚下载了新的Xcode 7.0测试版,并从Swift 1.2迁移到Swift 2.迁移显然没有改变整个代码,实际上是一个方法saveContext(),直到抛出2个错误为止:
if moc.hasChanges && !moc.save() {
和
该方法如下所示: // 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() } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |