NSPredicate在获取请求中将@max与其他条件一起使用 [英] NSPredicate that uses @max with an other condition in a fetch request
问题描述
我有一个CoreData实体 Song
,它具有日期属性 pushDate
和一个布尔属性 isPublic
.
I have a CoreData entity Song
that has date property pushDate
and a boolean property isPublic
.
我需要获取最新的公开歌曲.
I need to fetch the latest public song.
要获取最新消息,我可以使用-
To get the latest, I can use -
request.predicate = [NSPredicate predicateWithFormat:@"pushDate==max(pushDate)"];
但是当我尝试-
request.predicate = [NSPredicate predicateWithFormat:@"pushDate==max(pushDate) AND isPublic == YES"];
我没有任何结果(我100%确信我有公开== YES的歌曲).
I don't get any result (I am 100% sure that I have songs with public == YES).
我可以使用此谓词吗?如果没有,为什么/正确的方法是什么?
Can I use this predicate ? If no why / what is the correct way to do this ?
谢谢
推荐答案
我认为问题在于 max(pushDate)
是在所有歌曲中评估的,而不仅仅是公开歌曲.如果最新的歌曲(即符合第一个子句的 pushDate == max(pushDate)
)不是公开的,则它将使第二个子句失败( isPublic == YES
).
I think the problem is that max(pushDate)
is evaluated across ALL Songs, not just the public ones. If the most recent Song (ie the one that meets the first clause, pushDate == max(pushDate)
) is NOT public, then it will fail the second clause (isPublic == YES
).
如果要最新的公开歌曲",则必须先过滤掉这些公开歌曲,然后再查找最新的歌曲.
If you want "the most recent public song", then you must filter down to the public songs, before finding the most recent.
为此,我将使用仅获取公开歌曲的谓词:
To do that, I would use a predicate that fetches only public songs:
request.predicate = [NSPredicate predicateWithFormat:@"isPublic == YES"];
还要指定一个sortDescriptor,它按 pushDate
降序对结果进行排序:
And also specify a sortDescriptor that sorts the results in order of descending pushDate
:
request.sortDescriptors = [[NSSortDescriptor sortDescriptorWithKey:@"pushDate" ascending:NO]];
结果中的第一项将是您想要的歌曲.为了避免获取所有行,请使用:
The first item in the results will be the song you want. To avoid fetching all the rows, use:
request.fetchLimit = 1;
执行提取之前.
这篇关于NSPredicate在获取请求中将@max与其他条件一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!