Swift 2(executeFetchRequest):错误处理 [英] Swift 2 ( executeFetchRequest ) : error handling
问题描述
我遇到了我无法弄清楚的代码问题.安装Xcode 7 Beta并将我的Swift代码转换为Swift 2之后
I got some issue with the code that I can't figure out. After I installed Xcode 7 beta and convert my swift code to Swift 2
代码:
override func viewDidAppear(animated: Bool) {
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = AppDel.managedObjectContext
let request = NSFetchRequest(entityName: "PlayerList")
list = Context.executeFetchRequest(request)
tableView.reloadData()
}
屏幕截图:
推荐答案
从Swift 2开始,将产生错误的Cocoa方法转换为引发错误的Swift函数.
As of Swift 2, Cocoa methods that produce errors are translated to Swift functions that throw an error.
代替 Swift 1.x 中的可选返回值和错误参数:
Instead of an optional return value and an error parameter as in Swift 1.x:
var error : NSError?
if let result = context.executeFetchRequest(request, error: &error) {
// success ...
list = result
} else {
// failure
println("Fetch failed: \(error!.localizedDescription)")
}
在 Swift 2 中,该方法现在返回非可选值并引发错误 在错误情况下,必须使用try-catch进行处理:
in Swift 2 the method now returns a non-optional and throws an error in the error case, which must be handled with try-catch:
do {
list = try context.executeFetchRequest(request)
// success ...
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
有关更多信息,请参见采用可可粉"中的错误处理"设计模式" 在将Swift与Cocoa和Objective-C结合使用" 文档.
For more information, see "Error Handling" in "Adopting Cocoa Design Patterns" in the "Using Swift with Cocoa and Objective-C" documentation.
这篇关于Swift 2(executeFetchRequest):错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!