Swift从ManagedObjectContext FetchRequest获取日期数组

时间:2016-05-10 16:31:13

标签: ios arrays swift core-data nspredicate

我正在尝试为Core Data中的Date属性创建一个NSDate数组(保存日期数组)。因此,我可以在日历上显示保存项目的日期。我尝试过以下代码,但收到错误:

由于未捕获的异常终止应用' NSInvalidArgumentException',原因:'无法解析格式字符串" savedTime"

func datesWithSavedData() -> [NSDate] {
  let fetchRequest = NSFetchRequest(entityName: "UserData")
  fetchRequest.predicate = NSPredicate(format: "savedTime'")
  fetchRequest.sortDescriptors = [NSSortDescriptor(key: "savedTime", ascending: false)]
  do {
    let results =
      try managedObjectContext.executeFetchRequest(fetchRequest) as? [NSDate]
    selectedDates = results!
    print(selectedDates)
  } catch let error as NSError {
    print("Could not fetch \(error), \(error.userInfo)")
  }

  return selectedDates as! [NSDate]
}

1 个答案:

答案 0 :(得分:3)

解决方案是告诉Core Data返回字典数组而不是[NSManagedObject]例如

func datesWithSavedData() -> [NSDate] {
    let fetchRequest = NSFetchRequest(entityName: "UserData")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "savedTime", ascending: false)]
    fetchRequest.resultType = .DictionaryResultType
    fetchRequest.propertiesToFetch = ["savedTime"]
    do {
       let results = try managedObjectContext.executeFetchRequest(fetchRequest) as! [[String:NSDate]]
       return results.map { $0["savedTime"] as! NSDate }

    } catch let error as NSError {
       print(error)
       return [NSDate]()
    }
}

Swift 3 +

func datesWithSavedData() -> [Date] {
    let fetchRequest : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "UserData")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "savedTime", ascending: false)]
    fetchRequest.resultType = .dictionaryResultType
    fetchRequest.propertiesToFetch = ["savedTime"]
    do {
       let results = try managedObjectContext.fetch(fetchRequest) as! [[String:Date]]
       return results.map { $0["savedTime"] as! Date }

    } catch {
       print(error)
       return [Date]()
    }
}