在安装Xcode 7 Beta并将Swift代码转换为Swift 2之后,我遇到了一些我无法弄清楚的代码问题。我知道Swift 2是新手,所以我搜索并找出了答案,因为没有任何相关内容,我应该写一个问题。
这是错误:
可以抛出呼叫,但未将其标记为“ 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在下面的注释中指出的,通常最好的做法是不要在引发错误的地方捕获错误。您可以将方法标记为,throws然后try调用该方法。例如:
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() }