mahdiTGK mahdiTGK - 1 year ago 142
Swift Question

Cast from 'NSPersistentStoreResult' to unrelated type '[entity]' always fails

I am using Core Data in my app. I am facing trouble in fetching the results back from coredata. My entity name is Wonders.

Now I managed to successfully save a record. Now when I am fetching it back I am using the following code.

override func viewWillAppear(animated: Bool) {
let wondersAppdel:AppDelegate=UIApplication.sharedApplication().delegate as!AppDelegate
let WondersContext:NSManagedObjectContext = wondersAppdel.managedObjectContext
let wondersFetchRequest = NSFetchRequest(entityName: "Wonders")
wondersFetchRequest.predicate=NSPredicate(format: "wonderShow = %@", true)
let sortDescriptor = NSSortDescriptor(key: "wonderName", ascending: true)

do {
let wonderFetchresults = try WondersContext.executeRequest(wondersFetchRequest) as? [Wonders]{
wonders = wonderFetchresults
else{print("else if result...try")}
fatalError("there was an error fatching the list of gruops!")}

Answer Source

You should be calling executeFetchRequest method of NSManagedObjectContext when you are performing a NSFetchRequest.

try WondersContext.executeFetchRequest(wondersFetchRequest)