I have problem with sort array of arrays. I already build method to sort but it not work properly. I mean that final table should be sorted by last element, descending using the last element.
My method:
static NSInteger order (id a, id b, void* context)
{
NSNumber* catA = [a lastObject];
NSNumber* catB = [b lastObject];
return [ catB compare: catA];
}
And call it by:
[ array sortUsingFunction:order context:NULL];
And my array is sort that:
{1,9}
{1,6}
{1,5}
{2,2}
{0,18}
{12, 10}
{9,1}
Where is problem?
You don’t say exactly what is wrong with the array after you sort it. I see two possible problems.
As Eimantas says in his comment, you are sorting the array in reverse order (highest to lowest). If you want to sort lowest to highest, you need to say
return [catA compare:catB].It looks like the elements of
catAandcatBare strings, not numbers, so you are sorting them as strings. The string ’10’ is less than the string ‘9’, but the number 10 is greater than the number 9. Even though you are casting the elements toNSNumber, that does not change the type of the underlying object, which is stillNSString.You can sort them as numbers this way:
But it might be better to convert the strings to number objects before sorting the array: