2012-04-30 41 views
0

我有一個這樣的數組值:{蘋果,王后,微軟,50cent}。我想在最後對數組字母順序和50cent進行排序。我正在用下面的方法做,但它排序頂部50cent:與數字按字母順序排序之初

[albums sortUsingDescriptors:[NSArray arrayWithObject: 
            [[[NSSortDescriptor alloc] 
            initWithKey:@"name" 
            ascending:YES 
            selector:@selector(localizedCaseInsensitiveCompare:)] 
            autorelease]]]; 
+0

http://stackoverflow.com/questions/8242735/how-to-sort-array-controller-alphabetically-with-numbers-last-in-objective-c –

回答

5

您可以使用comparator blocks

在你的情況下,該塊應該做以下幾點:

  • 檢查兩個字符串的第一個字母,都是他們兩個數字或字母,做return [obj1 compare:obj2]

  • 如果第一個對象開頭一些但有字母,return NSOrderedAscending,如果它是周圍的其他方式,第二,return NSOrderedDescending

得到第一個字母,使用[obj1 substringToIndex:1]


這一理念的完整代碼:

NSArray *array = [NSArray arrayWithObjects:@"peach",@"apple",@"banana",@"ananas",@"50cents", @"papaya", nil]; 

array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { 
    NSString *s1 = [obj1 substringToIndex:1]; 
    NSString *s2 = [obj2 substringToIndex:1]; 

    if ([s1 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location == [s2 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location) { 
     return [obj1 compare:obj2]; 
    } else { 
     if ([s1 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location == NSNotFound) { 
      return NSOrderedAscending; 
     } 
    } 
    return NSOrderedDescending; 
}]; 

當您使用sortUsingDescriptors:,你必須使用的NSMutableArray。您可以就地使用與比較排序與sortUsingComparator:

[array sortUsingBlock:<The block stays the same>]; 
+0

真棒的感謝! – rocky