我已经创建了一个排序描述符来对来自我的服务器的plist响应进行排序。当排序关键字的值不超过9时,这种方法效果很好。当排序关键字的值超过10个时,我会看到突然的结果,排序关键字的顺序为= 1,10,11,2,3,4,5,6,7,8,9
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sort" ascending:YES];
self.myList = [NSMutableArray arrayWithArray:[unsortedList sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]];如何让它按照1,2,3,4,5,6,7,8,9,10,11的正确顺序排列?
发布于 2012-03-13 05:11:42
您可以通过在创建NSSortDescriptor时实现自定义比较器块来完成此操作
NSSortDescriptor *aSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES comparator:^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
self.myList = [NSMutableArray arrayWithArray:[unsortedList sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]];请参阅苹果文档here
发布于 2012-03-13 05:20:23
[list sortUsingSelector:@selector(localizedStandardCompare:)];将以“人”的方式对列表进行排序(因此"11“将排在最后,而不是在"1”和“2”之间)。但是如果你真的想把这些字符串当做数字来处理,你应该先把它们变成数字!
发布于 2013-03-26 21:38:25
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sort.intValue" ascending:YES];
self.myList = [NSMutableArray arrayWithArray:[unsortedList sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]];根据整数的值进行排序。
https://stackoverflow.com/questions/9674707
复制相似问题