我需要反转NSArray。
举个例子:
[1,2,3,4,5]必须变成:[5,4,3,2,1]
实现这一目标的最佳方式是什么?
我需要反转NSArray。
举个例子:
[1,2,3,4,5]必须变成:[5,4,3,2,1]
实现这一目标的最佳方式是什么?
当前回答
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特性,以及评论中的一些技巧。)
其他回答
Swift 3语法:
let reversedArray = array.reversed()
反向枚举数组的最有效方法:
使用enumerateObjectsWithOptions:NSEnumerationReverse usingBlock。使用@JohannesFahrenkrug上面的基准测试,这比[[array reverseObjectEnumerator] allObjects]快8倍;:
NSDate *methodStart = [NSDate date];
[anArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//
}];
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime = %f", executionTime);
如果你想做的只是反向迭代,试试这个:
// iterate backwards
nextIndex = (currentIndex == 0) ? [myArray count] - 1 : (currentIndex - 1) % [myArray count];
你可以做一次[myArrayCount],并将其保存到一个局部变量(我认为这很昂贵),但我也猜测编译器将对上面写的代码做同样的事情。
一些基准
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显然是赢家。
有一个简单的方法。
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"]
我希望这能有所帮助。