Sunday, May 15, 2016

Get Data from Core Data

Assuming you already added an entity to your *.xcdatamodeld file, this is how you would get all entities.
func getRecipes() {
    let app = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = app.managedObjectContext
    let fetchRequest  = NSFetchRequest(entityName: "MyEntity")
    
    do {
        let results = try context.executeFetchRequest(fetchRequest)
        recipes = results as! [Recipe]
    } catch let err as NSError {
        print(err.debugDescription)
    }
}

Possible Errors and Resolutions


EXC_BAD_INSTRUCTION

Execution breaks in the AppDelegate.managedObjectModel property. This happens when you are not including (targeting) the *.xcdatamodeld for your app. Fix by clicking on your *.xcdatamodeld file and go to File Inspector pane on the right and put a checkmark next to your app name under "Target Membership".

Unable to load class

Full Error: CoreData: warning: Unable to load class named '______' for entity '______'. Class not found, using default NSManagedObject instead.
When you auto-generated your NSManagedObject Subclass, you should have had a "@objc(MyEntity)" above it. Do not delete this, put it back in. Or just copy your code, regenerate the managed object class and paste your code back in.
(Swift 2.2)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...