2017-08-02 26 views
0

我有一個具有Date屬性的實體。現在我只想檢索不超過5分鐘的條目。核心數據僅檢索不超過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

它看起來像你有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已經在一個版本的快速變化