开发者

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"
arrayOb开发者_如何学Pythonj 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 @[];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜