快速核心数据查询不适用于今天的日期



我有一个由CoreData管理的名为Places的类。该对象有一个Date对象作为时间戳。

我有这个查询只探测今天的位置。问题是,我今天只有2个地方登录,但它产生了我21条记录,我不希望

func updatePlaceMarksForADateFromDatabase(date: Date) {
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "UTC")!
let dateFrom = calendar.startOfDay(for: date)
let dateTo = calendar.date(byAdding: .day, value: 1, to: dateFrom)

// Set predicate as date being compliant with date
let fromPredicate = NSPredicate(format: "%@ >= %@", date as NSDate, dateFrom as NSDate)
let toPredicate = NSPredicate(format: "%@ < %@", date as NSDate, dateTo! as NSDate)
let datePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate, toPredicate])
// CoreData API's to list only today places
let fetchRequest: NSFetchRequest<Places> = Places.fetchRequest()
fetchRequest.predicate = datePredicate
if let context = (UIApplication.shared.delegate as? AppDelegate)?
.persistentContainer.viewContext {
let sort = NSSortDescriptor(key: #keyPath(Places.timestamp), ascending: false)
fetchRequest.sortDescriptors = [sort]
if let placesCoreData = try?
context.fetch(fetchRequest) {
// Store it to the cache
print(placesCoreData.count)
}
}
}

你的断言是错误的。

let fromPredicate = NSPredicate(format: "%@ >= %@", date as NSDate, dateFrom as NSDate)
let toPredicate = NSPredicate(format: "%@ < %@", date as NSDate, dateTo! as NSDate)
let datePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate, toPredicate])

您不是针对Places的属性测试它。目前,它等于NSPredicate(value: true),因为date大于或等于dateFrom,小于dateTo。它应该始终为真(根据如何创建值)。这就是为什么你在抓取的时候会得到所有的地方。

应该是:

let fromPredicate = NSPredicate(format: "%K >= %@", argumentArray: [#keyPath(Places.dateVariableName), dateFrom]
let toPredicate = NSPredicate(format: "%K < %@", argumentArray: [#keyPath(Places.dateVariableName), dateTo]

相关内容

  • 没有找到相关文章

最新更新