0

Possible Duplicate:
How can I reverse a NSArray in Objective-C?

I want sort the NSArray descending by index.

I can sort array values how can I sort by index...

NSArray* arr = [[NSArray alloc] initWithObjects:@"First",@"Second",@"Third",@"Fifth",@"Last",nil];

The result should be like this

  • Last
  • Fifth
  • Third
  • Second
  • First

Is there any direct method available in iOS?

Community
  • 1
  • 1
Codesen
  • 7,724
  • 5
  • 29
  • 31
  • try to lost in the `-sortedArrayUsingDescriptors:` method or any other -sortedArray...` methods. they really help you in your problem, if you want custom order of the elements. – holex Aug 02 '12 at 11:39
  • I am going to guess that you are asking: "Is there something that will translate words into numbers", ie that recognizes "first", "second" etc. The answer to that is no. If you decide to do your own, then as others said, you can easily sort by first translating the word to a number yourself in code, then sorting on that number. – David H Aug 02 '12 at 12:05
  • No, I just want to descending array by index. Don't worry about the value of the array. It might be any object. – Codesen Aug 02 '12 at 12:08

2 Answers2

5

If you just want to reverse the array, there is an elegant way to do it.

I found the solution in this answer by danielpunkass.

NSArray *reversedArray = [[originalArray reverseObjectEnumerator] allObjects];
Community
  • 1
  • 1
matsr
  • 4,302
  • 3
  • 21
  • 36
0
NSMutableArray *array = ...;
[array sortUsingComparator: ^(id obj1, id obj2) {
    _NSComparisonResult result = [obj1 compare:obj2]; // [NSString compare:]
    if (result == NSOrderedAscending)
        return NSOrderedDescending;
    if (result == NSOrderedDescending)
        return NSOrderedAscending;
    return NSOrderedSame;
}];

OR

NSMutableArray *array = ...;
[array sortUsingComparator: ^(id obj1, id obj2) {
    _NSComparisonResult result = [obj1 compare:obj2]; // [NSString compare:]
    return -result; // minus result
}];

See apple documents about NSArray -sortUsingComparator:

NSObjCRuntime.h

enum _NSComparisonResult {NSOrderedAscending = -1, NSOrderedSame, NSOrderedDescending};

booiljoung
  • 776
  • 6
  • 10