在我安装了 Xcode 7 beta 并将我的 swift 代码转换为 Swift 2 之后,我遇到了一些我无法弄清楚的代码问题。我知道 Swift 2 是新的,所以我搜索并弄清楚,因为它什么都没有,我应该写一个问题。
这是错误:
call 可以抛出,但是没有标记 ‘try’ 并且错误没有处理
代码:
func deleteAccountDetail(){ let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!) let request = NSFetchRequest() request.entity = entityDescription //The Line Below is where i expect the error let fetchedEntities = self.Context!.executeFetchRequest(request) as! [AccountDetail] for entity in fetchedEntities { self.Context!.deleteObject(entity) } do { try self.Context!.save() } catch _ { } }
快照:
您必须像您已经为您的save()呼叫所做的那样捕获错误,并且由于您在这里处理多个错误,您可以try在单个 do-catch 块中按顺序进行多次调用,如下所示:
save()
try
func deleteAccountDetail() { let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!) let request = NSFetchRequest() request.entity = entityDescription do { let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail] for entity in fetchedEntities { self.Context!.deleteObject(entity) } try self.Context!.save() } catch { print(error) } }
或者正如@bames53 在下面的评论中指出的那样,最好不要在抛出错误的地方捕获错误。您可以将方法标记为throwsthentry以调用该方法。例如:
throws
func deleteAccountDetail() throws { let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!) let request = NSFetchRequest() request.entity = entityDescription let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail] for entity in fetchedEntities { self.Context!.deleteObject(entity) } try self.Context!.save() }