In iOS 10 the CoreData team added a new "fetchRequest" method to NSManagedObject. It looks like this:
public class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult>
Which, from what I understand, allows us to replace this:
let request = NSFetchRequest<MyEntity>(entityName: "MyEntity")
with this:
let request = MyEntity.fetchRequest()
However, when I try to make a simple request like this:
let request = MyEntity.fetchRequest()
do {
results = try request.execute()
} catch let error {
print("failed to fetch coffee object: \(error)")
}
I receive the following error:
Error Domain=NSCocoaErrorDomain Code=134060 "(null)" UserInfo={message=Cannot fetch without an NSManagedObjectContext in scope}
So, clearly the error is stating that I need to bring an NSManagedObjectContext into scope. I've been looking for examples but can seem to find a full example of how to perform a request using the new API features.
Question
Using the latest Core Data API features, how do I make a simple fetch request? The underlying question is how do I bring my NSmanagedObjectCotnext into scope.
I should note that I am able to successfully make a request using the traditional syntax.
as!
downcasting you're doing is no longer necessary-- the results of the fetch should already have a type of[MyEntity]
. – Saiva