我该如何在Objective中反转一个NSArray
我需要扭转我的NSArray
。
举个例子:
[1,2,3,4,5]
必须变成: [5,4,3,2,1]
达到此目的的最佳方法是什么?
要获得数组的反转副本,请使用reverseObjectEnumerator
查看danielpunkass的解决方案。
为了反转可变数组,您可以将以下类别添加到您的代码中:
@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
还有一个更简单的解决方案,如果你利用内置的reverseObjectEnumerator
对方法NSArray
和allObjects
的方法NSEnumerator
:
NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];
allObjects
记录为按照以下allObjects
返回一个数组,其中尚未遍历nextObject
的对象:
该数组包含按枚举顺序排列的枚举数的所有剩余对象。
一些基准
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]
在速度和易用性方面是明显的赢家。
上一篇: How can I reverse a NSArray in Objective
下一篇: How can I add CGPoint objects to an NSArray the easy way?