i want to sort an array of integers with multiple digits in ascending order.
Here is my Array:
keyArray:
(
978,
1077,
1067,
1076,
1072,
1082,
1079,
1075,
1071,
1081,
1078,
1080,
1074
)
Here is my code:
NSSortDescriptor *sortOrder = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending: YES];
NSArray *sortedArray2 = [keyArray sortedArrayUsingComparator:^(id str1, id str2) {
if ([str1 integerValue] < [str2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([str1 integerValue] > [str2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
NSLog(@"%@",[keyArray sortedArrayUsingDescriptors: [NSArray arrayWithObject:sortOrder]]);
Problem is that this will sort the array like this
sortedArray: (
1067,
1071,
1072,
1074,
1075,
1076,
1077,
1078,
1079,
1080,
1081,
1082,
978
)
it will sort four digit numbers first, then three digit numbers.
You can achieve what you want really easy, try this: