Objective-C,sorting包含数字的string数组

让我们假设我有一个这样的数组

NSArray* arr = @[@"1",@"4",@"2",@"8",@"11",@"10",@"14",@"9"]; //note: strings containing numbers 

我想这样sorting:[1,2,4,8,9,10,11,14]

但如果我使用

 [arr sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 

我得到[1,10,11,14,2,4,8,9] …如果我使用:

  NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:YES]; NSArray *sortDescriptors = @[sortDescriptor]; [arr sortedArrayUsingDescriptors:sortDescriptors]; 

我得到这样的东西:[1,4,2,8,9,11,10,14]

我怎样才能结合这两个谓词? 或者是解决这个问题的其他更简单的方法? 注意:这个数组的输出只是为了debugging目的,我不在乎如果结果将数组转换为整数,只要我可以在控制台与NSLog谢谢

尝试使用块

 [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { if ([obj1 intValue] == [obj2 intValue]) return NSOrderedSame; else if ([obj1 intValue] < [obj2 intValue]) return NSOrderedAscending; else return NSOrderedDescending; }]; 

问题是,你正在尝试使用string比较和-length来拼凑你真正想要的,这是数字比较。 但是sorting描述符一次只能应用一个,而第二个描述符只有在第一个描述符按照相同的顺序排列时才被使用。 使用-intValue对项目进行sorting,可以使用单个sorting描述符按照您的要求sorting项目。

做这个,而不是:

 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"intValue" ascending:YES]; [arr sortedArrayUsingDescriptors:@[sortDescriptor]];