NSPredicate Sort Array and Order DESC

拜拜、爱过 提交于 2019-12-22 13:55:11

问题


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"]];

回答1:


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;

}];


来源:https://stackoverflow.com/questions/8393205/nspredicate-sort-array-and-order-desc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!