-1

i am workinng on timer app. i have a an array.i want to sort array in accending order. suppose i have 5 element in array like 10,100,50,30,70.

I want array like 10,30,50,70,100.

ravinder521986
  • 722
  • 9
  • 17

6 Answers6

11
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id firstObject, id secondObject) {
    return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
}];

EDIT: If the elements are numbers, change the returned type and the type of the firstObject and secondObject.

o15a3d4l11s2
  • 3,969
  • 3
  • 29
  • 40
3

from apple's documentation

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {

    if ([obj1 integerValue] > [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }

    if ([obj1 integerValue] < [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];
John Corbett
  • 1,595
  • 10
  • 19
2

Use sortedArrayUsingComparator

NSArray *arr = @[@3, @2, @6, @1];
NSArray *sorted = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    if ([obj1 intValue] < [obj2 intValue]) return NSOrderedAscending;
    else return NSOrderedDescending;
}];
James Webster
  • 31,873
  • 11
  • 70
  • 114
0
 NSArray * arr=[[NSArray alloc]initWithObjects:[NSNumber   numberWithInt:10],[NSNumber   numberWithInt:100],[NSNumber   numberWithInt:50],[NSNumber   numberWithInt:30],[NSNumber   numberWithInt:70], nil];
    NSLog(@"Before sorting%@",arr);

    arr = [arr sortedArrayUsingSelector:@selector(compare:)];
      NSLog(@"After sorting%@",arr);
Rams
  • 1,721
  • 12
  • 22
-2
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]]];
Rahul Vyas
  • 28,260
  • 49
  • 182
  • 256
  • There is no need to create the `NSSortDescriptor` you can use `sortedArrayUsingComparator:` methode with the same block. – rckoenes Aug 08 '12 at 12:29
-2

use this code:

NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id firstObject, id secondObject) {
    return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
}];

EDIT: If the elements are numbers, change the returned type and the type of the firstObject and secondObject.

Luke
  • 11,426
  • 43
  • 60
  • 69
Vineesh TP
  • 7,755
  • 12
  • 66
  • 130