我不能拼凑如何做到这一点。
我从一个plist中获取我的数组,这个数组充满了数字(在plist中设置)。现在我需要做的就是对它们进行排序以便它们正在下降,但我无法解决它。
试试这个代码?
NSArray *array = /* loaded from file */;
array = [array sortedArrayUsingSelector: @selector(compare:)];
以下将按升序对数字进行排序,然后反转结果以按降序给出数字:
NSArray *sorted = [[[array sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];
之前的问题还有其他一些选择:Sort an NSArray in Descending Order
这是使用比较块的许多方法之一。此代码段对于包含要排序的数字的任何数组都很方便。对于升序:
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;
}];
它对我有用:
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];
这将解决问题:
NSArray *array = /* loaded from file */;
array = [array sortedArrayUsingSelector: @selector(compare:)];