简体   繁体   中英

How to inverse the contents of NSArray in Objective-C?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM