我从核心数据中获取。我有一个属性是一个用时间属性保存的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
}
}
答案 0 :(得分:0)
如果您要返回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
包含已过滤的项目。