Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting from 'NSPersistentStoreResult' to unrelated type 'Entity' always fails

I am creating a small app to learn the many to many relationships in CoreData. However using the code below I get an error casting from my NSFetchResult to my Entity class ('Groepering'):

enter image description here

I do not see any difference from samples I found on the internet compared to my project, why does the cast still fail?

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext  let fetchRequest : NSFetchRequest = NSFetchRequest(entityName: "Entity")      do {         let fetchResults = try managedContext.executeRequest(fetchRequest)         let groeperingen = fetchResults as! [Entity]         // Here I get the Error: ^      } catch {         print("Error") } 
like image 998
Emptyless Avatar asked Apr 18 '16 09:04

Emptyless


2 Answers

Use executeFetchRequest method of NSManagedObjectContext when performing a NSFetchRequest.

Edit Swift 3: For Swift 3, use:

let result = try managedContext.fetch(fetchRequest) 
like image 87
Ahmed Onawale Avatar answered Oct 06 '22 00:10

Ahmed Onawale


I recently converted my code to Swift 3 and ran into this same error, though not because of a typo. It seems that the new, equivalent function call is let fetchResults = try managedContext.fetch(fetchRequest).

like image 28
blwinters Avatar answered Oct 06 '22 00:10

blwinters