Search
Filters
Blog options
Close

How to write a fetch request using Core Data and Swift 3

How to write a fetch request using Core Data and Swift 3

This is an excerpt from a Stack Overflow discussion, which you can find here.

 

Ok, I figured out two ways of doing this. The first approach, which is similar to my example code is just simply:

var moc: NSManagedObjectContext!
let request = MyEntity.fetchRequest()
var results : [MyEntity]

 do {
     results = try moc.fetch(request)
 } catch { // error stuff}

The second approach, which was shown in WWDC 2016 uses a function named "execute" on our fetch request object.

If you view the details on NSFetchRequest you'll see a comment that clearly states that the operation must be performed with in a block.

// Executes the fetch request using the current managed object context. This method must be called from within a block submitted to a managed object context.
    @available(iOS 10.0, *)
    public func execute() throws -> [ResultType]

It's dawned on me that this was the way to perform the fetch:

var moc: NSManagedObjectContext!
let request = MyEntity.fetchRequest()
var results : [MyEntity]

moc.perform {
    self.results = try! request.execute()
}

For those who roll their own If you are rolling your own code you may find that your code does not compile. Included in the auto-generated code is a new method called fetchRequest that the compiler uses to pass the type along. Here's what the code looks like.

@nonobjc public class func fetchRequest() -> NSFetchRequest {
    return NSFetchRequest(entityName: "MyEntity");
}