Alan
Alan

Reputation: 9481

SortedArrayUsingComparator not working accurately

I am trying to sort my array, but it seems to not work reliably.

Here is the code for sorting. Basically the Request priorityID has values from 1-5 For example: enter image description here

 sortedArray = [self.selectedReqArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
            NSLog(@"Value A: %@", [NSNumber numberWithInteger:[(Request*)a priorityID]]);
            NSLog(@"Value B %@", [NSNumber numberWithInteger:[(Request*)b priorityID]]);
            NSNumber *first = [NSNumber numberWithInt:[(Request*)a priorityID]];
            NSNumber *second = [NSNumber numberWithInt:[(Request*)b priorityID]];
            return [first compare:second];
        }];

        self.sortedReqArray = [NSMutableArray arrayWithArray:sortedArray];

Sometimes it's sorting correctly 1-5, but sometimes it sorts 1 2 4 5 3...

Then when I go to take a look at the NSLog it's spitting out really big values when they should just be 1-5.

Here is sample output Value B 168492640 Value A: 168492640 Value B 168492640 Value A: 174580912 Value B 168492640 Value A: 174580912 Value B 168492640 Value A: 174580912 Value B 168492640 Value A: 174580912 Value B 168492640 Value A: 174580912

What is happening? Thank you!

Upvotes: 0

Views: 2747

Answers (1)

Martin R
Martin R

Reputation: 539975

From the debugger display [(Request*)a priorityID] seems to be a NSNumber, but you are treating it as integer (so you are actually comparing the addresses of the objects).

This following should work:

sortedArray = [self.selectedReqArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
            NSNumber *first = [(Request*)a priorityID];
            NSNumber *second = [(Request*)b priorityID];
            return [first compare:second];
        }];

A perhaps slightly more elegant way to write this is

sortedArray = [self.selectedReqArray sortedArrayUsingComparator:^NSComparisonResult(Request* a, Request* b) {
            NSNumber *first = [a priorityID];
            NSNumber *second = [b priorityID];
            return [first compare:second];
        }];

If the Request class is Key-Value Coding compliant for the key priorityID, the following should also work:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"priorityID" ascending:YES];
sortedArray = [self.selectedReqArray sortedArrayUsingDescriptors:@[sort]];

Upvotes: 3

Related Questions