gpt4 book ai didi

ios - Swift 2 : Call can throw, 但未标记为 'try' 错误未处理

转载 作者:行者123 更新时间:2023-11-28 08:11:39 33 4
gpt4 key购买 nike

在我安装 Xcode 7 beta 并将我的 swift 代码转换为 Swift 2 之后,我遇到了一些我无法弄清楚的代码问题。我知道 Swift 2 是新的,所以我搜索并弄清楚了,因为没有关于它的任何内容,我应该写一个问题。

这是错误:

Call can throw, but it is not marked with 'try' and the error is not handled

代码:

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 _ {
}

}

快照: enter image description here

最佳答案

您必须像您已经为 save() 调用所做的那样捕获错误,并且由于您在此处处理多个错误,您可以尝试多个在单个 do-catch block 中按顺序调用,如下所示:

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 调用该方法。例如:

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

关于ios - Swift 2 : Call can throw, 但未标记为 'try' 错误未处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43594854/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com