4

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.

Blixt
  • 49,547
  • 13
  • 120
  • 153
suse
  • 10,503
  • 23
  • 79
  • 113

3 Answers3

30
NSArray* reversed = [[originalArray reverseObjectEnumerator] allObjects];
ig2r
  • 2,396
  • 1
  • 16
  • 17
4

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
  • 2,046
  • 1
  • 13
  • 8
0

Or the Scala-way:

-(NSArray *)reverse
{
    if ( self.count < 2 )
        return self;
    else
        return [[self.tail reverse] concat:[NSArray arrayWithObject:self.head]];
}

-(id)head
{
    return self.firstObject;
}

-(NSArray *)tail
{
    if ( self.count > 1 )
        return [self subarrayWithRange:NSMakeRange(1, self.count - 1)];
    else
        return @[];
}