【问题标题】:Core Data retrive only elements which are not older than 5minCore Data 仅检索不超过 5 分钟的元素
【发布时间】:2017-08-02 08:56:36
【问题描述】:

我有一个具有 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: []) 不可用。

【问题讨论】:

    标签: swift core-data nspredicate


    【解决方案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 的版本中发生了变化

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 2014-01-20
      • 2013-10-28
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多