How Do I sort an NSMutable Array with NSNumbers in it?

后端 未结 7 2071
星月不相逢
星月不相逢 2020-12-05 02:06

I\'m trying to make a high score table, and suck at arrays in objective c (actually, in general objective c is challenging for me), so I can\'t figure out how to sort. I\'m

7条回答
  •  日久生厌
    2020-12-05 02:14

    This code will sort an NSMutableArray of NSNumber in ascending order:

    [tempRA sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2];
    }];
    

    This code will sort an NSMutableArray of NSNumber in descending order:

    [tempRA sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2] * -1; // reverse the enum
    }];
    

    The code uses the fact that the NSNumber compare: method returns an NSComparisonResult that ranges from -1 to 1. Multiplying the result of the compare by -1 reverses the result and thereby reverses the sort to descending order.

提交回复
热议问题