4

I want to display data in UITableView in reverse order. I manage to do it with little effort but can any one provide a better way to do it. Thanks in advance.

rdp
  • 2,072
  • 4
  • 31
  • 55

3 Answers3

31

Use -[NSArray reverseObjectEnumerator]:

NSArray * a = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
NSArray * reverse = [[a reverseObjectEnumerator] allObjects];
NSLog(@"%@", reverse);  //logs "c, b, a"
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
15

Well i dont know what your code is but you can do something like this

cell.title = [anarray objectAtIndex:(anarray.count - indexPath.row - 1)];

Hope this may works. Cheers.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
Robin
  • 10,011
  • 5
  • 49
  • 75
2

There is a much easier solution, if you take advantage of the built-in reverseObjectEnumerator method on NSArray, and the allObjects method of NSEnumerator:

NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];
Zagham Arshad
  • 111
  • 1
  • 7
  • 1
    That *is* a pretty good solution, but I notice that Dave DeLong suggested the same thing 2.5 years ago. Did you miss his answer? – Caleb Jul 09 '13 at 04:21
  • 1
    Its also an exact copy and paste of this answer by somebody else from almost 4 years ago here: http://stackoverflow.com/a/586529/1026573 – James Kuang Dec 10 '14 at 21:04