我从核心数据中提取。我有一个属性,它是一个bool,与time属性一起保存。我需要返回布尔值为真的日期数组。我不能让它工作,我要么得到一系列空日期,要么它崩溃。
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
}
}
最佳答案
如果返回aDate
和aBool
,则返回值不能小于cc>
let results = try managedObjectContext.fetch(fetchRequest) as! [[String:Any]]
不筛选代码中的项,而是将筛选条件添加到谓词中
fetchRequest.predicate = NSPredicate(format: "harveyBradshawIndexSaveLevel = %@ AND savedTime == TRUE", messageKey as CVarArg)
现在
[[String:Date]]
包含已筛选的项。关于swift - 具有多个sortDescriptors和Bool过滤器的Swift fetchRequest,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39687870/