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