0

Here is the code I use to sort items in an NSMutableArray. The code works without errors but after applying the filter, the order doesn't change. Am I doing something wrong?

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;
}];
6
  • 2
    "the order doesn't change" - are you checking order of posts or filtered? Commented Jun 14, 2013 at 7:43
  • 1
    The NSComparisonResult casts are completely unneccessary. Also, your p1 and p2 variables are strange, since they are taking only the double of the count (and they should be NSUInteger). Sorting by double value is equivalent to sorting just by value. Commented Jun 14, 2013 at 7:44
  • Are you checking the order of filtered or posts? Is the NSOrderedSame return always reached when the block is executed? Commented Jun 14, 2013 at 7:45
  • @CodaFi Right, if the firstPhotoVoters are nil or empty, the order won't change. Commented Jun 14, 2013 at 7:46
  • @Sulthan the cast is necessary for LLVM < 5.0 due to the odd quasi-type inference of blocks. Commented Jun 14, 2013 at 7:46

2 Answers 2

1

You could put breakpoints on return NSOrderedAscending and return NSOrderedDescending, log firstPhotoVoters.count for both objects to see if something unexpected is happening. The code is fine apart from the fact that you could use

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

instead of

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

and nothing would change, its a waste of cycles.

Sign up to request clarification or add additional context in comments.

2 Comments

When you say the order doesn't change, you do mean the order of filtered compared to posts?
Right side of the sum operator should be secondPhotoVoters.count. Thanks for the help.
0
int p1 = post1.firstPhotoVoters.count + post1.firstPhotoVoters.count;
int p2 = post2.firstPhotoVoters.count + post2.firstPhotoVoters.count;

You are using the same property twice. There should be probably a different property as one of the operands.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.