Core Data in swift 2

Struggling with the syntax a bit, is there an example anywhere?


I have a snippet of code here:

let request = NSFetchRequest(entityName: "StockCode")
request.predicate = NSPredicate(format: "ean == %@", ean)
let results = managedContext.executeFetchRequest(request) as! [StockCode]

Basically finding a product code from a bit list of them.

The last line is giving "Call can throw, but it is not marked with try and the error is not handled"

If I was better with try/catch historically, then I may be able to solve it, but I've tried a few things and cant solve it. I'd really appreciate some help if there's enough info here to be able to. Thanks.

Answered by hirad in 11646022

Watch the "What's New in Swift" talk. Since `executeFetchRequest` is a throwing method (https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/index.html#//apple_ref/occ/instm/NSManagedObjectContext/executeFetchRequest:error:), you need to wrap it in a `do { ... } catch { ... }`.
So I think it should look like this:


do {
  ... 
  let results = try managedContext.executeFetchRequest(request) as! [StockCode]
}
catch {
  fatalError("Fetching from the store failed")
}



This is based on my take away from the talk. I still haven't downloaded Xcode 7 :[

Accepted Answer

Watch the "What's New in Swift" talk. Since `executeFetchRequest` is a throwing method (https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/index.html#//apple_ref/occ/instm/NSManagedObjectContext/executeFetchRequest:error:), you need to wrap it in a `do { ... } catch { ... }`.
So I think it should look like this:


do {
  ... 
  let results = try managedContext.executeFetchRequest(request) as! [StockCode]
}
catch {
  fatalError("Fetching from the store failed")
}



This is based on my take away from the talk. I still haven't downloaded Xcode 7 :[

Yup, that's pretty much it.

I had watched that, which gave me an awareness so I then jumped into a conversion without proper study! Turns out I was trying "try let results = ..." rather than "let results = try...." as the first one seemed more logical but I get it now.


Cheers for the reply 🙂

Core Data in swift 2
 
 
Q