I can\'t piece together how to do this.
I fetch my array from a plist, this array is full of numbers (as set in the plist). Now al I need to do is sort them so they are
Here is one of many methods using comparison block. This code snippet is handy for any array with numbers that you want to sort. For Ascending 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;
}];
For Descending order:
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;
}];
It work for me:
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];
Try this code?
NSArray *array = /* loaded from file */;
array = [array sortedArrayUsingSelector: @selector(compare:)];
This Will solve the problem:
NSArray *array = /* loaded from file */;
array = [array sortedArrayUsingSelector: @selector(compare:)];
The following will sort the numbers in ascending order and then reverse the result to give the numbers in descending order:
NSArray *sorted = [[[array sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];
This previous question has some other alternatives: Sort an NSArray in Descending Order