Venkat Venkat - 5 months ago 8
iOS Question

How to sort an Array of signed numbers in iOS?

This may be a simple question, but i don't know the way of doing sorting of array of signed integer values.

My array before sorting,

pointsAry (-2,-7,-5,0,-3,2,-1,-4,1,3,-6)


After using

NSArray * sortedArray = [pointsAry sortedArrayUsingComparator:^(id str1, id str2){
return [(NSString *)str1 compare:(NSString *)str2 options:NSNumericSearch];
}];


Result

sortedArray : (-1,-2,-3,-4,-5,-6,-7,0,1,2,3)


for signed values the sortedArray format is not correct, so i need like

(-7,-6,-5,-4,-3,-2,-1,0,1,2,3)


How to sort like above format ? Thanks in advance.

Answer
NSArray *sortedArray = [pointsAry sortedArrayUsingComparator:^(NSString *str1, NSString *str2){
    return [@([str1 intValue]) compare:@([str2 intValue])];
}];
Comments