views:

50

answers:

2

Hello,

How do i inverse the contents of NSArray in Objective-C?

Assume that i have an array which holds these data

NSArray arrayObj = [[NSArray alloc]init];
arrayObj atindex 0 holds this: "1972"
arrayObj atindex 1 holds this: "2005"
arrayObj atindex 2 holds this: "2006"
arrayObj atindex 3 holds this: "2007"

Now i want to inverse the order of array like this:

arrayObj atindex 0 holds this: "2007"
arrayObj atindex 1 holds this: "2006"
arrayObj atindex 2 holds this: "2005"
arrayObj atindex 3 holds this: "1972"

How to achive this??

Thank You.

+1  A: 

Iterate over your array in reverse order and create a new one whilst doing so:

NSArray *originalArray = [NSArray arrayWithObjects:@"1997", @"2005", @"2006", @"2007",nil];

NSMutableArray *newArray = [[NSMutableArray alloc] initWithObjects:nil];

for (int i = [originalArray count]-1; i>=0; --i)
{
    [newArray addObject:[originalArray objectAtIndex:i]];
}
Gauloises
can u please tel me in code .
suse
Jop, edited my post acccordingly
Gauloises
doesn't the reversionhappen if the array value is in string i.e"1972/05/03""2005/08/02""2006/02/06""2006/03/10"
suse
ig2r's answer is better anyways ^^
Gauloises
+10  A: 
NSArray* reversed = [[originalArray reverseObjectEnumerator] allObjects];
ig2r