mahdiTGK mahdiTGK - 4 months ago 42
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)
wondersFetchRequest.sortDescriptors=[sortDescriptor]



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

Answer

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

try WondersContext.executeFetchRequest(wondersFetchRequest)