Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

swift2 - Swift 2 ( executeFetchRequest ) : error handling

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

Code:

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

ScreenShot:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As of Swift 2, Cocoa methods that produce errors are translated to Swift functions that throw an error.

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

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

For more information, see "Error Handling" in "Adopting Cocoa Design Patterns" in the "Using Swift with Cocoa and Objective-C" documentation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...