2

我写了两个单独的函数fetchRecordsdisplayRecords写在AppdelegateClass中。fetchRecords函数将从实体中获取所有记录,并且工作正常。displayRecordsfunction 接受 function 的返回值,fetchRecords并一一打印所有记录。

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

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

这是用 AppDelegate 类编写的fetchRecords和函数displayRecords

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

3 回答 3

3

问题是它AppDelegate()总是创建一个与应用程序的“硬编码”委托实例不同的类的新实例。

你必须写

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)")
    }
}
于 2016-04-29T10:57:39.567 回答
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"))")
        }
    }
}

这里的关键变化是让仪表板=数据为!仪表板。仪表板是您需要在核心数据模型帮助下创建的托管对象子类。

于 2016-04-29T10:49:40.820 回答
0

试试这个。。

let dashboard = Dashboard as! NSManagedObject

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

我认为它可能会奏效。因为您已将 ManagedObject 作为data。最好把它当作一种Dashboard。这样您就可以通过 dashboardObj.count 访问count ..

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

希望能帮助到你..

于 2016-04-29T10:28:35.397 回答