Reputation: 888
My tableView app loads the data into the table view.
Everything works perfectly, but the array sorting is kind of messed, like you can see in the picture below. I thought about using the sortedArrayUsingSelector, to straighten things up, but I'm not sure which "sorting method" I should use.
How can I sort this so the cells are sorted according the numbers? Like the order would be 1. 2. 3. 4. 5. etc NOT 1. 10. 11. 12. 13. 14. 2. 3. ?
Thanks a lot in advance!!
Upvotes: 3
Views: 2036
Reputation: 80271
And a two-liner:
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES comparator:^(id obj1, id obj2) { return [obj1 compare:obj2 options:NSNumericSearch]; }];
rowTitleArray = [rowTitleArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
Upvotes: 5
Reputation: 80271
Here is a more elegant solution:
NSInteger intSort(id num1, id num2, void *context) {
NSString *n1 = (NSString *) num1;
NSString *n2 = (NSString *) num2;
n1 = [[n1 componentsSeparatedByString:@"."] objectAtIndex:0];
n2 = [[n2 componentsSeparatedByString:@"."] objectAtIndex:0];
if ([n1 intValue] < [n2 intValue]) {
return NSOrderedAscending;
}
else if ([n1 intValue] > [n2 intValue]) {
return NSOrderedDescending;
}
return NSOrderedSame;
}
rowTitleArray = [rowTitleArray sortedArrayUsingFunction:intSort context:NULL];
Upvotes: 1
Reputation: 80271
Sorry for this convoluted approach, but this does work...
NSArray *rowTitleArray = [[NSArray alloc] initWithObjects:
@"10. Tenth",
@"15. Fifteenth",
@"13. Thirteenth",
@"1. First",
@"2. Second",
@"22. TwentySecond", nil];
NSMutableArray *dictionaryArray = [NSMutableArray array];
for (NSString *original in rowTitleArray) {
NSString *numberString = [[original componentsSeparatedByString:@"."] objectAtIndex:0];
NSNumber *number = [NSNumber numberWithInt:[numberString intValue]];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
number, @"number", original, @"rowTitle", nil];
[dictionaryArray addObject:dict];
}
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"number" ascending:YES];
NSArray *sortedDictionaryArray = [dictionaryArray sortedArrayUsingDescriptors:
[NSArray arrayWithObject:descriptor]];
NSMutableArray *sortedRowTitles = [NSMutableArray array];
for (NSDictionary *dict in sortedDictionaryArray) {
[sortedRowTitles addObject:[dict objectForKey:@"rowTitle"]];
}
rowTitleArray = [NSArray arrayWithArray:sortedRowTitles];
NSLog(@"%@", rowTitleArray);
Output:
"1. First", "2. Second", "10. Tenth", "13. Thirteenth", "15. Fifteenth", "22. TwentySecond"
I will try to think of a more elegant solution.
Upvotes: 1