简体   繁体   English

核心数据-NSManagedObject返回nil

[英]Core Data - NSManagedObject returning nil

I wrote two seperate functions fetchRecords and displayRecords written in Appdelegate Class. 我用Appdelegate类编写了两个单独的函数fetchRecordsdisplayRecords fetchRecords function will fetch all records from the entity and it is working fine. fetchRecords函数将从实体中获取所有记录,并且工作正常。 displayRecords function accepts the return value from fetchRecords function and prints all the records one by one. displayRecords函数接受displayRecords函数的返回值,并fetchRecords打印所有记录。

I have one view controller which calls these two functions to do the desired task. 我有一个视图控制器,它调用这两个函数来完成所需的任务。 My problem is result.count in displayRecords shows the total number of records available in fetched records.While printing the records one by one the value is nil. 我的问题是displayRecords中的result.count显示获取的记录中可用的记录总数。虽然一一打印记录,但值为nil。

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

And here is the fetchRecords and displayRecords functions written in AppDelegate Class 这是用AppDelegate类编写的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"))")
        }
    }
}

Adding my data model here 在这里添加我的数据模型 在此处输入图片说明

I will share the data insertion code also. 我还将共享数据插入代码。

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

The issue is that AppDelegate() creates always a new instance of the class which is not the same as the "hard-coded" delegate instance of the application. 问题是AppDelegate()始终创建该类的新实例,该实例与应用程序的“硬编码”委托实例不同。

You have to write 你必须写

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

Since you have created a custom subclass of NSManagedObject use it as type rather than NSManagedObject or – worse – the unspecified AnyObject . 由于创建了NSManagedObject的自定义子类,因此将其用作类型,而不是NSManagedObject或更糟糕的是未指定的AnyObject It makes many things much easier: 它使许多事情变得容易得多:

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

Try this one.. 试试这个

let dashboard = Dashboard as! NSManagedObject

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

I think it might work. 我认为这可能有效。 Because you have taken your ManagedObject as data . 因为您已将ManagedObject当作data Better you take it as kind of Dashboard . 最好把它当作仪表板 So that you can access count by dashboardObj.count .. 这样您就可以通过dashboardObj.count访问计数

Hope you created Core Data NSManagedSubclass for the Entity. 希望您为实体创建了核心数据NSManagedSubclass。

Hope it helps.. 希望能帮助到你..

Create a NSManagedObject subclass of Dashboard from your coredata model. 根据您的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"))")
        }
    }
}

Key change here is let dashboard = data as! 这里的关键更改是让仪表板=数据为! Dashboard. 仪表板。 Dashboard is managed object subclass which you need to create with core data model help. 仪表板是您需要在核心数据模型帮助下创建的托管对象子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM