NSPredicate 对数组进行排序并按 DESC 顺序

发布于 2024-12-19 11:15:15 字数 369 浏览 4 评论 0原文

我有一个包含 TBPostsNSMutableArray,我想根据其 commentsCountlikesCount 按降序过滤TBPost

最初,过滤数组中的第一个对象将是评论和点赞数量最多的对象,可以通过将两者相加得出。因此,我尝试了以下查询并收到无法解析错误。请问你能告诉我哪里出错了吗?

[posts filterUsingPredicate:[NSPredicate predicateWithFormat:@"post.commentsCount + post.likesCount DESC"]];

I have an NSMutableArray containing TBPosts that I would like to filter in descending order according to the commentsCount and likesCount of the TBPost.

Initially, the first object in the filtered array will be the object with the largest number of comments and likes, which can be worked out by adding the two together. So I tried the following query and receive an Unable to Parse error. Please can you tell me where I am going wrong?

[posts filterUsingPredicate:[NSPredicate predicateWithFormat:@"post.commentsCount + post.likesCount DESC"]];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

維他命╮ 2024-12-26 11:15:15

过滤不是排序。您使用了错误的方法。

使用比较器,它看起来像这样:

[posts sortUsingComparator:^NSComparisonResult(id p1, id p2) {
    if (p1.commentsCount + p1.likesCount < p2.commentsCount + p2.likesCount)
        return (NSComparisonResult)NSOrderedAscending;
    if (p1.commentsCount + p1.likesCount > p2.commentsCount + p2.likesCount)
        return (NSComparisonResult)NSOrderedDescending;
    return (NSComparisonResult)NSOrderedSame;

}];

filtering is not sorting. You are using the wrong method.

Using a comparator, it would look like this:

[posts sortUsingComparator:^NSComparisonResult(id p1, id p2) {
    if (p1.commentsCount + p1.likesCount < p2.commentsCount + p2.likesCount)
        return (NSComparisonResult)NSOrderedAscending;
    if (p1.commentsCount + p1.likesCount > p2.commentsCount + p2.likesCount)
        return (NSComparisonResult)NSOrderedDescending;
    return (NSComparisonResult)NSOrderedSame;

}];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文