tableView中的疯狂数组排序! sortedArrayUsingSelector帮助?

时间:2011-08-16 20:22:16

标签: iphone ios uitableview sorting nsarray

我的tableView应用将数据加载到表格视图中。 一切都很完美,但数组排序有点乱,就像你在下面的图片中看到的那样。我想过使用sortedArrayUsingSelector来理顺,但我不确定应该使用哪种“排序方法”。 You can see, the numbers don't go like 1. 2. 3. 4. 5. etc, but weird...

如何对此进行排序,以便根据数字对单元格进行排序?喜欢的顺序是1. 2. 3. 4. 5. etc NOT 1. 10. 11. 12. 13. 14. 2. 3.?

提前多多感谢!!

3 个答案:

答案 0 :(得分:5)

还有两个班轮:

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES comparator:^(id obj1, id obj2) { return [obj1 compare:obj2 options:NSNumericSearch]; }];
rowTitleArray = [rowTitleArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];

答案 1 :(得分:1)

对于这种错综复杂的方法感到抱歉,但这确实有用......

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);

输出:

    "1. First",
    "2. Second",
    "10. Tenth",
    "13. Thirteenth",
    "15. Fifteenth",
    "22. TwentySecond"

我会尝试考虑更优雅的解决方案。

答案 2 :(得分:1)

这是一个更优雅的解决方案:

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];