0

这是我用来对 NSMutableArray 中的项目进行排序的代码。代码可以正常工作,但应用过滤器后,顺序不会改变。难道我做错了什么?

NSArray *filtered = [posts sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    Post *post1 = (Post *)obj1;
    Post *post2 = (Post *)obj2;

    int p1 = post1.firstPhotoVoters.count + post1.firstPhotoVoters.count;
    int p2 = post2.firstPhotoVoters.count + post2.firstPhotoVoters.count;

    if (p1 < p2) return (NSComparisonResult)NSOrderedAscending;
    if (p1 > p2) return (NSComparisonResult)NSOrderedDescending;

    return (NSComparisonResult)NSOrderedSame;
}];
4

2 回答 2

1

return NSOrderedAscending您可以在和上设置断点return NSOrderedDescending,记录firstPhotoVoters.count这两个对象以查看是否发生了意外情况。代码很好,除了你可以使用

int p1 = post1.firstPhotoVoters.count;
int p2 = post2.firstPhotoVoters.count;

代替

int p1 = post1.firstPhotoVoters.count + post1.firstPhotoVoters.count;
int p2 = post2.firstPhotoVoters.count + post2.firstPhotoVoters.count;

什么都不会改变,这是浪费周期。

于 2013-06-14T08:00:06.230 回答
0
int p1 = post1.firstPhotoVoters.count + post1.firstPhotoVoters.count;
int p2 = post2.firstPhotoVoters.count + post2.firstPhotoVoters.count;

您两次使用相同的属性。可能应该有一个不同的属性作为操作数之一。

于 2013-06-14T08:03:34.143 回答