Core data - why does fetch query return nil?

I have some code that fetches the basic data

    var appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    var managedContext : NSManagedObjectContext = appDelegate.managedObjectContext!
    let request = NSFetchRequest(entityName: "QuestionDB")
    request.returnsObjectsAsFaults = false
    if let results = managedContext.executeFetchRequest(request, error: nil)

      

it returns an array AnyObject

I need it to return an array of objects with type [Question]

when i quit

    var appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    var managedContext : NSManagedObjectContext = appDelegate.managedObjectContext!
    let request = NSFetchRequest(entityName: "QuestionDB")
    request.returnsObjectsAsFaults = false
    if let results = managedContext.executeFetchRequest(request, error: nil) as? [Question] {
        println("This is result of loadFromDb \(results)")
    }

      

it returns nil

How can I fix this?

+3


source to share


2 answers


Check the class name in the Entity data model inspector in the data model for

select application .xcdatamodeld

select Entity

and indata model inspector



enter image description here

+1


source


Try the following:

    let fetchRequest = NSFetchRequest(entityName:"QuestionDB")

    var error: NSError?

    let fetchedResults = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) as! [NSManagedObject]?

    if let results = fetchedResults {
        return results  as! [QuestionDB]
    } else {
        fatalError("Could not fetch \(error), \(error!.userInfo)")
    }

      



If your class name Question

you have to set it in the model inspector.

0


source







All Articles