Ne vous contentez pas
return [self.name compare:otherObject.name options:(NSCaseInsensitiveSearch)];
Mais faire quelques vérifications supplémentaires, par exemple si self.name commence par un non-numeral et otherObject.name commence par un chiffre, puis retourne NSDescendingOrder, et vice versa. IOW, faites un chiffre> non numérique. Si les deux sont non numéraux ou les deux sont des chiffres, retournez ce que vous avez déjà eu.
Ce petit programme de console explique le principe que je veux dire:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *array = [NSMutableArray arrayWithObjects:
@"Adam", @"001", @"Bertha", @"3SeriesBMW", @"Colin",
@"Zelda", @"1And1", @"Xaver", @"Kraftwerk", @"TangerineDream",
@"5SeriesBMW", @"0ableTypes", nil];
NSString *sortOrder = @"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz_";
[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
char char1 = [(NSString *)obj1 characterAtIndex: 0];
char char2 = [(NSString *)obj2 characterAtIndex: 0];
int index1;
for (index1 = 0; index1 < sortOrder.length; index1++)
if ([sortOrder characterAtIndex: index1] == char1)
break;
int index2;
for (index2 = 0; index2 < sortOrder.length; index2++)
if ([sortOrder characterAtIndex: index2] == char2)
break;
if (index1 < index2)
return NSOrderedAscending;
else if (index1 > index2)
return NSOrderedDescending;
else
return [(NSString *)obj1 compare: obj2 options: NSCaseInsensitiveSearch];
}];
for (NSString *s in array)
NSLog(@"%@", s);
[pool drain];
return 0;
}
La sortie est:
2011-08-25 14:19:15.538 NumeralSort[5802:707] Adam
2011-08-25 14:19:15.540 NumeralSort[5802:707] Bertha
2011-08-25 14:19:15.540 NumeralSort[5802:707] Colin
2011-08-25 14:19:15.540 NumeralSort[5802:707] Kraftwerk
2011-08-25 14:19:15.541 NumeralSort[5802:707] TangerineDream
2011-08-25 14:19:15.541 NumeralSort[5802:707] Xaver
2011-08-25 14:19:15.541 NumeralSort[5802:707] Zelda
2011-08-25 14:19:15.542 NumeralSort[5802:707] 001
2011-08-25 14:19:15.542 NumeralSort[5802:707] 0ableTypes
2011-08-25 14:19:15.542 NumeralSort[5802:707] 1And1
2011-08-25 14:19:15.543 NumeralSort[5802:707] 3SeriesBMW
2011-08-25 14:19:15.543 NumeralSort[5802:707] 5SeriesBMW
Ce n'est pas exactement la solution, mais si vous obtenez sur votre chemin.
Ça a marché, merci pour votre aide! – steemcb
comment puis-je l'utiliser dans NSSortDescriptor? – Raj