问题
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