SmokersCough
SmokersCough

Reputation: 967

Order an NSMutable array in descending order

I've been reading a few posts about ordering an NSMutable array but have had trouble getting it working, essentially I have a number of entries in a tableview, an unlimited amount can be added but I need to order them by an NSMutable array that contains numerical values, that would go well above 10. I'd really appreciate any help anyone could give me, I've been using the compare parameter but I can't seem to get it to reverse the order, secondly I read that numbers above 10 would start ordering in a strange way. Ill post y code shortly but anything for me to mull over would be great.

Thanks

Upvotes: 3

Views: 1603

Answers (1)

Martin R
Martin R

Reputation: 539725

The answer depends a bit on whether the objects in your array are numbers or strings. There are also various methods to sort arrays (sortUsingDescriptors, sortUsingComparator, ...).

If you have an array of numbers, you can sort them in decreasing order for example like this:

NSMutableArray *a = [NSMutableArray arrayWithObjects:@1, @55, @9, @17, nil];
[a sortUsingComparator:^NSComparisonResult(NSNumber *obj1, NSNumber *obj2) {
    return -[obj1 compare:obj2];
}];
// Result: 55, 17, 9, 1.

Note the minus-sign in the comparator block which has the effect of reversing the order from increasing to decreasing.

If you have an array of strings, and you proceed in the same way, then you will get what you have called "that numbers above 10 would start ordering in a strange way":

NSMutableArray *a = [NSMutableArray arrayWithObjects:@"1", @"55", @"9", @"17", nil];
[a sortUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
    return -[obj1 compare:obj2];
}];
// Result: 9, 55, 17, 1.

The object are sorted as strings, not as numbers.

The solution is to use the NSNumericSearch option:

NSMutableArray *a = [NSMutableArray arrayWithObjects:@"1", @"55", @"9", @"17", nil];
[a sortUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
    return -[obj1 compare:obj2 options:NSNumericSearch];
}];
// Result: 55, 17, 9, 1.

Upvotes: 7

Related Questions