核心数据 - NSManagedObject返回nil

时间:2016-04-29 10:07:59

标签: ios core-data nsfetchrequest swift2.2

我写了两个用fetchRecords类编写的单独函数displayRecordsAppdelegatefetchRecords函数将从实体获取所有记录并且工作正常。displayRecords函数接受来自fetchRecords函数的返回值并逐个打印所有记录。

我有一个视图控制器,它调用这两个函数来完成所需的任务。我的问题是result.count displayRecords显示了获取记录中可用的记录总数。在逐个打印记录时,值为nil。

override func viewDidLoad() {
super.viewDidLoad()
    let fetchedRecords = AppDelegate().fetchRecords(fromEntity: "Dashboard")
    AppDelegate().displayRecords(fromFetchedRecords: fetchedRecords)   
}

这是用AppDelegate Class编写的fetchRecordsdisplayRecords函数

  func fetchRecords(fromEntity entity:String) -> Array<AnyObject> {
    var fetchedResult:Array<AnyObject> = []
    let fetchRequest = NSFetchRequest()
    let entityDescription = NSEntityDescription.entityForName(entity, inManagedObjectContext: self.managedObjectContext)!
    fetchRequest.entity = entityDescription
    do{
        fetchedResult = try self.managedObjectContext.executeFetchRequest(fetchRequest)              
    }catch{
        let fetchError = error as NSError?
        print(fetchError!)
    }
   return fetchedResult
}

func displayRecords(fromFetchedRecords result:Array<AnyObject>) {
    print("Total records:\(result.count)")
    if (result.count > 0) {
        for data in result {
        let dashboard = data as! NSManagedObject
        print("Value: \(dashboard.valueForKey("count"))")
        }
    }
}

在此处添加我的数据模型 enter image description here

我也会分享数据插入代码。

func saveDashBoardData(dictionary: Dictionary<String, String>) {
    print(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask))

    //Create Manage Object
    let entityDescription: NSEntityDescription = NSEntityDescription.entityForName("Dashboard", inManagedObjectContext: self.managedObjectContext)!
    for data in dictionary {
        let dashboardObject = Dashboard(entity: entityDescription,insertIntoManagedObjectContext: self.managedObjectContext)
        dashboardObject.type  = data.0
        dashboardObject.count = data.1
        do {
            try self.managedObjectContext.save()
            print("Data saved succesfully")
        }
        catch {
            print(error)
        }
    }
}

3 个答案:

答案 0 :(得分:3)

问题是AppDelegate()始终创建一个类的新实例,它与&#34;硬编码&#34;不同。委托应用程序的实例。

你必须写

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let fetchedRecords = appDelegate.fetchRecords(fromEntity: "Dashboard")
appDelegate.displayRecords(fromFetchedRecords: fetchedRecords)

由于您已创建NSManagedObject的自定义子类,因此将其用作类型而不是NSManagedObject或 - 更糟 - 未指定的AnyObject。它使许多事情变得更容易:

func fetchRecords(fromEntity entity:String) -> [Dashboard] {
  let fetchRequest = NSFetchRequest()
  let entityDescription = NSEntityDescription.entityForName(entity, inManagedObjectContext: self.managedObjectContext)!
  fetchRequest.entity = entityDescription
  do {
     return try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [Dashboard]              
  } catch let fetchError as NSError {
     print(fetchError!)
  }
  return [Dashboard]()
}

func displayRecords(fromFetchedRecords result:[Dashboard]) {
    print("Total records:\(result.count)")

    for dashboard in result { // the check for empty is not needed
       print("Value: \(dashboard.count)")
    }
}

答案 1 :(得分:0)

试试这个..

let dashboard = Dashboard as! NSManagedObject

print("Value: \(dashboard.count)")

我认为它可能会奏效。因为您已将ManagedObject作为数据。最好将其视为仪表板。因此,您可以通过dashboardObj.count ..

访问计数

希望您为实体创建Core Data NSManagedSubclass。

希望有所帮助......

答案 2 :(得分:0)

从coredata模型创建Dashboard的NSManagedObject子类。

func displayRecords(fromFetchedRecords result:Array<AnyObject>) {

    print("Total records:\(result.count)")
    if (result.count > 0) {
        for data in result {
        let dashboard = data as! Dashboard
        print("Value: \(dashboard.valueForKey("count"))")
        }
    }
}

此处的关键更改是让dashboard =数据为!仪表板。 仪表板是托管对象子类,您需要使用核心数据模型帮助创建该子类。