核心数据 - 为什么获取请求返回nil?

时间:2015-07-29 12:22:28

标签: ios swift core-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)

返回AnyObject

数组

我需要它返回类型为[Question]

的对象数组

当我施展

    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)")
    }

它返回nil

我该如何解决?

2 个答案:

答案 0 :(得分:1)

通过

检查数据模型中实体的数据模型检查器中的类名

选择您的应用.xcdatamodeld - > select Entitydata model inspector

enter image description here

答案 1 :(得分:0)

试试这个:

    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)")
    }

如果您的班级名称为Question,则必须在模型检查员中进行设置。