【问题标题】:Swift fetchRequest with multiple sortDescriptors and Bool filter带有多个 sortDescriptor 和 Bool 过滤器的 Swift fetchRequest
【发布时间】:2016-09-25 14:19:56
【问题描述】:

我正在从核心数据中获取。我有一个布尔属性,它与时间属性一起保存。我需要返回一个布尔值为真的日期数组。我无法让它工作,我要么得到一个空日期数组,要么崩溃。

func datesWithCompleteHBI() -> [Date] {

  let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
  fetchRequest.resultType = .dictionaryResultType
  fetchRequest.propertiesToFetch = ["savedTime", "harveyBradshawIndexComplete"]

  let timeSort = NSSortDescriptor(key: "savedTime", ascending: false)
  let hbiSort = NSSortDescriptor(key: "harveyBradshawIndexComplete", ascending: false)
  fetchRequest.sortDescriptors = [timeSort, hbiSort]

  let messageKey = true
  fetchRequest.predicate = NSPredicate(format: "harveyBradshawIndexSaveLevel = %@", messageKey as CVarArg)

  var dates = [Date]()
  do {

      let results = try managedObjectContext.fetch(fetchRequest) as! [[String:Date]]

      dates = results.flatMap { $0["savedTime"]}

     } catch let error as NSError {
       print("Could not fetch \(error), \(error.userInfo)")

    }

 print("hbi date array \(dates)")
 return dates
 }
}

【问题讨论】:

    标签: swift nsdate nspredicate nsfetchrequest nssortdescriptor


    【解决方案1】:

    如果您要返回 DateBool,则返回值不能是 [[String:Date]]

    let results = try managedObjectContext.fetch(fetchRequest) as! [[String:Any]]
    

    不是过滤代码中的项目,而是将过滤条件添加到谓词

    fetchRequest.predicate = NSPredicate(format: "harveyBradshawIndexSaveLevel = %@ AND savedTime == TRUE", messageKey as CVarArg)
    

    现在results 包含过滤后的项目。

    【讨论】:

    • 谢谢,我收到一个错误无法使用类型为 '(([String : Any]) throws -> Bool)' 的参数列表调用 'filter'
    • 我更新了答案。过滤谓词中的对象是更好的解决方案。
    • 对不起,这没有成功。感谢您的帮助。当我弄清楚时,我会发布答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    相关资源
    最近更新 更多