我需要反转NSArray。

举个例子:

[1,2,3,4,5]必须变成:[5,4,3,2,1]

实现这一目标的最佳方式是什么?


当前回答

有一个简单的方法。

    NSArray *myArray = @[@"5",@"4",@"3",@"2",@"1"];
    NSMutableArray *myNewArray = [[NSMutableArray alloc] init]; //this object is going to be your new array with inverse order.
    for(int i=0; i<[myNewArray count]; i++){
        [myNewArray insertObject:[myNewArray objectAtIndex:i] atIndex:0];
    }
    //other way to do it
    for(NSString *eachValue in myArray){
        [myNewArray insertObject:eachValue atIndex:0];
    }

    //in both cases your new array will look like this
    NSLog(@"myNewArray: %@", myNewArray);
    //[@"1",@"2",@"3",@"4",@"5"]

我希望这能有所帮助。

其他回答

反向数组并循环遍历它:

[[[startArray reverseObjectEnumerator] allObjects] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    ...
}];

有一个更简单的解决方案,如果你利用NSArray内置的reverseObjectEnumerator方法,以及NSEnumerator的allObjects方法:

NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];

allObjects被记录为返回一个数组,其中的对象还没有被nextObject遍历,顺序如下:

该数组按枚举顺序包含枚举器的所有剩余对象。

要获得数组的反向副本,请参阅danielpunkass使用reverseObjectEnumerator的解决方案。

为了反转一个可变数组,你可以在你的代码中添加以下类别:

@implementation NSMutableArray (Reverse)

- (void)reverse {
    if ([self count] <= 1)
        return;
    NSUInteger i = 0;
    NSUInteger j = [self count] - 1;
    while (i < j) {
        [self exchangeObjectAtIndex:i
                  withObjectAtIndex:j];

        i++;
        j--;
    }
}

@end

一些基准

1. reverseObjectEnumerator allObjects

这是最快的方法:

NSArray *anArray = @[@"aa", @"ab", @"ac", @"ad", @"ae", @"af", @"ag",
        @"ah", @"ai", @"aj", @"ak", @"al", @"am", @"an", @"ao", @"ap", @"aq", @"ar", @"as", @"at",
        @"au", @"av", @"aw", @"ax", @"ay", @"az", @"ba", @"bb", @"bc", @"bd", @"bf", @"bg", @"bh",
        @"bi", @"bj", @"bk", @"bl", @"bm", @"bn", @"bo", @"bp", @"bq", @"br", @"bs", @"bt", @"bu",
        @"bv", @"bw", @"bx", @"by", @"bz", @"ca", @"cb", @"cc", @"cd", @"ce", @"cf", @"cg", @"ch",
        @"ci", @"cj", @"ck", @"cl", @"cm", @"cn", @"co", @"cp", @"cq", @"cr", @"cs", @"ct", @"cu",
        @"cv", @"cw", @"cx", @"cy", @"cz"];

NSDate *methodStart = [NSDate date];

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

NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime = %f", executionTime);

结果:executionTime = 0.000026

2. 迭代一个reverseObjectEnumerator对象

这要慢1.5到2.5倍:

NSDate *methodStart = [NSDate date];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[anArray count]];
NSEnumerator *enumerator = [anArray reverseObjectEnumerator];
for (id element in enumerator) {
    [array addObject:element];
}
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime = %f", executionTime);

结果:executionTime = 0.000071

3.sortedArrayUsingComparator

这要慢30到40倍(这里没有意外):

NSDate *methodStart = [NSDate date];
NSArray *reversed = [anArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
    return [anArray indexOfObject:obj1] < [anArray indexOfObject:obj2] ? NSOrderedDescending : NSOrderedAscending;
}];

NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime = %f", executionTime);

结果:executionTime = 0.001100

因此,当谈到速度和易用性时,[[anArray reverseObjectEnumerator] allObjects显然是赢家。

DasBoot有正确的方法,但是在他的代码中有一些错误。这是一个完全通用的代码片段,它将反转任何NSMutableArray:

/* Algorithm: swap the object N elements from the top with the object N 
 * elements from the bottom. Integer division will wrap down, leaving 
 * the middle element untouched if count is odd.
 */
for(int i = 0; i < [array count] / 2; i++) {
    int j = [array count] - i - 1;

    [array exchangeObjectAtIndex:i withObjectAtIndex:j];
}

你可以把它包装在一个C函数中,或者为了加分,使用类别将它添加到NSMutableArray中。(在这种情况下,'array'将变成'self'。)如果您愿意,还可以通过在循环之前将[array count]分配给一个变量并使用该变量来优化它。

如果你只有一个常规的NSArray,没有办法在适当的地方反转它,因为NSArray不能被修改。但是你可以反向复制:

NSMutableArray * copy = [NSMutableArray arrayWithCapacity:[array count]];

for(int i = 0; i < [array count]; i++) {
    [copy addObject:[array objectAtIndex:[array count] - i - 1]];
}

或者用这个小技巧把它写在一行里:

NSArray * copy = [[array reverseObjectEnumerator] allObjects];

如果你只是想向后循环一个数组,你可以使用[array reverseObjectEnumerator]的for/in循环,但使用-enumerateObjectsWithOptions:usingBlock::可能会更有效一些。

[array enumerateObjectsWithOptions:NSEnumerationReverse
                        usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    // This is your loop body. Use the object in obj here. 
    // If you need the index, it's in idx.
    // (This is the best feature of this method, IMHO.)
    // Instead of using 'continue', use 'return'.
    // Instead of using 'break', set '*stop = YES' and then 'return'.
    // Making the surrounding method/block return is tricky and probably
    // requires a '__block' variable.
    // (This is the worst feature of this method, IMHO.)
}];

(注:2014年进行了大幅更新,增加了5年的Foundation经验,一两个新的Objective-C特性,以及评论中的一些技巧。)