核心数据只检索不超过5分钟的元素

时间:2017-08-02 08:56:36

标签: swift core-data nspredicate

我有一个具有Date属性的实体。现在我只想检索不超过5分钟的条目。

到目前为止我试过这个。

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ContactRequest")

// Create a sort descriptor object that sorts on the "title"
// property of the Core Data object
let sortDescriptor = NSSortDescriptor(key: "request_time", ascending: true)

// Set the list of sort descriptors in the fetch request,
// so it includes the sort descriptor
fetchRequest.sortDescriptors = [sortDescriptor]

let originalDate = Date() // "Jun 13, 2016, 1:23 PM"
let calendar = Calendar.current
let limitDate = calendar.date(byAdding: .minute, value: -5, to: originalDate, options: [])

// Create a new predicate that filters out any object that
// doesn't have a title of "Best Language" exactly.
let predicate = NSPredicate(format: "request_time > %@", limitDate)

// Set the predicate on the fetch request
fetchRequest.predicate = predicate

但是xCode说calendar.date(byAdding: .minute, value: -5, to: originalDate, options: [])不可用。

1 个答案:

答案 0 :(得分:1)

看起来你的api错了。变化

let limitDate = calendar.date(byAdding: .minute, value: -5, to: originalDate, options: [])

let limitDate = calendar.date(byAdding: .minute, value: -5, to: originalDate, wrappingComponents: true)

请参阅: https://developer.apple.com/documentation/foundation/calendar/2293453-date

我不确定你为什么要options代替wrappingComponents。也许api在swift版本中有所改变