核心数据 - NSManagedObject 返回 nil

Core Data - NSManagedObject returning nil

我用 Appdelegate Class 编写了两个单独的函数 fetchRecordsdisplayRecordsfetchRecords 函数将从实体中获取所有记录,并且工作正常。displayRecords 函数接受来自 fetchRecords 函数的 return 值,并一一打印所有记录。

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

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

在此处添加我的数据模型

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

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

试试这个..

let dashboard = Dashboard as! NSManagedObject

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

我认为它可能有效。因为您已将 ManagedObject 作为 data。最好将其视为一种 仪表板 。这样您就可以通过 dashboardObj.count 访问 count ..

希望您为实体创建了核心数据 NSManagedSubclass。

希望对您有所帮助..

从您的核心数据模型创建 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 = data as!仪表盘。 仪表板是您需要使用核心数据模型帮助创建的托管对象子类。

问题是 AppDelegate() 总是创建一个 class 的新实例,它与应用程序的 "hard-coded" 委托实例不同。

你必须写

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

由于您已经创建了 NSManagedObject 的自定义子 class,因此将其用作类型而不是 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)")
    }
}