我刚刚下载了新的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。
原文链接:https://www.f2er.com/swift/320627.html为了反映这一点,在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() } } }