我无法拼凑如何做到这一点。
我从plist中获取我的数组,这个数组充满了数字(在plist中设置)。现在,我需要做的就是对它们进行排序,使它们下降,但我无法解决它。
答案 0 :(得分:39)
试试这段代码?
NSArray *array = /* loaded from file */;
array = [array sortedArrayUsingSelector: @selector(compare:)];
答案 1 :(得分:13)
以下将按升序对数字进行排序,然后反转结果以按降序给出数字:
NSArray *sorted = [[[array sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];
此前一个问题还有其他一些选择: Sort an NSArray in Descending Order
答案 2 :(得分:12)
这是使用比较块的许多方法之一。此代码段对于包含要排序的数字的任何数组都很方便。 对于升序:
AscendingArray = [UnsortArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
对于降序:
DescendingArray = [UnsortArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];
答案 3 :(得分:5)
对我有用:
NSSortDescriptor *sortIdClient =
[NSSortDescriptor sortDescriptorWithKey:@"campaignValue"
ascending:NO
comparator: ^(id obj1, id obj2){
return [obj1 compare:obj2 options:NSNumericSearch];
}];
NSArray *sortDescriptors = @[sortIdClient];
NSArray *arrTemp = [self.allCampaignsList sortedArrayUsingDescriptors:sortDescriptors];
答案 4 :(得分:0)
这将解决问题:
NSArray *array = /* loaded from file */;
array = [array sortedArrayUsingSelector: @selector(compare:)];