[英]NSPredicate Maximum time with swift2
I am using coredata and I want to find maximum time in coredata. 我正在使用coredata,我想在coredata中找到最大时间。 How do I write?
我该怎么写?
let predicate = NSPredicate(format: "contentDate = '???' ", "")
fetchRequest.predicate = predicate
To find a maximum it makes more sense to sort and ask for the first item than to try to create a predicate. 要找到最大值,排序并要求第一项比尝试创建谓词更有意义。
You can also look at an expression using @max to get the value back on its own if the container object isn't important. 如果容器对象不重要,您还可以使用@max查看表达式以自行返回值。
As Wain said, to find maximum value you rather have to define SortDescriptor
then Predicate
: 正如Wain所说,要找到最大值,您必须先定义
SortDescriptor
然后再定义Predicate
:
let sortByTimeDescriptor = NSSortDescriptor(key: "time", ascending: false)
fetchRequest.sortDescriptors = [sortByTimeDescriptor]
You are interested just in the one (maximum) value so it's also good practice to set fetch limit for performance reason: 您仅对一个(最大值)值感兴趣,因此出于性能原因设置获取限制也是一种很好的做法:
fetchRequest.fetchLimit = 1
Then just execute request and get first object from results array: 然后只需执行请求并从结果数组中获取第一个对象:
let results = managedObjectContext.executeFetchRequest(fetchRequest)
let maxTimeEntity = results.first
Notice that executeFetchRequest
can throw and error and you have to handle it somehow. 请注意,
executeFetchRequest
可能会引发错误,并且您必须以某种方式进行处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.