如何在Objective-C中反转NSArray的内容?
假设我有一个包含这些数据的数组
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"
如何实现这一目标?
谢谢。
答案 0 :(得分:30)
NSArray* reversed = [[originalArray reverseObjectEnumerator] allObjects];
答案 1 :(得分:4)
以相反的顺序迭代你的数组并创建一个新的数组:
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]];
}
答案 2 :(得分:0)
或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 @[];
}