Question

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.

Was it helpful?

Solution

NSArray* reversed = [[originalArray reverseObjectEnumerator] allObjects];

OTHER TIPS

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]];
}

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 @[];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top