In the last tutorial, we looked at the sortedArrayUsingComparator method which allows you to run a comparison on objects in an array and rearrange the objects in the array. In this tutorial we will look at a simple method which can be used to reverse the order of the contents of an array. Just be aware that this tutorial is quite brief as the code is relatively simple to use… it’s just a single line if you already have an NSArray to use.
Lets say you have 5 NSStrings which are a,b,c,d,e. When we iterate through these they will come out in the order of a,b,c,d,e. What if we want to show this information in a table view, but in reverse order? i.e., e,d,c,b,a. We do this with the reverseObjectEnumerator method of NSArray.
The way we do this is extremely simple:
NSArray *historyArray = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",@"d",@"e", nil];
historyArray = [[historyArray reverseObjectEnumerator] allObjects];
In the example above, we are creating an NSArray called historyArray and initialising it with 5 NSStrings… a, b, c, d, e.
On line 2, we use the reverseObjectEnumerator instance method and then call the allObjects method from NSEnumerator on that. The result is stored back in historyArray.
If you iterate through the historyArray before and after line 2, you will see that objects a,b,c,d,e are now ordered e,d,c,b,a with just a line of code. This of course, works with any type of object in an NSArray although I initialised with NSStrings just to cut down on the sample code.
Leave a Reply
You must be logged in to post a comment.