swift - 核心数据只检索不早于 5 分钟的元素

标签 swift core-data nspredicate

我有一个带有日期属性的实体。现在我只想检索不早于 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: []) 不可用。

最佳答案

看来你的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。可能是某个swift版本的api变了

关于swift - 核心数据只检索不早于 5 分钟的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45456098/

相关文章:

swift - 如何与核心数据建立多对多关系? swift ,xcode

ios - 推送通知在前台不起作用

iphone - 核心数据删除崩溃

swift - swift 中的 NSPredicate 用于空字符串

ios - 更改tableView中的值

swift - 如何将 indexPath 数组拆分为单独的 indexPath 数组,每个数组的 indexPath 具有相同的 indexPath.section

iOS 将文件下载到文件系统?

下次我打开应用程序时,Swift Filled plist 是空的

objective-c - NSPredicate 101 : Using NSPredicate with a NSMutableArray of custom objects

objective-c - LIKE 和 CONTAINS[cd] 有什么区别?