如何在Objective-C中反转NSArray?我需要扭转我的态度NSArray。举个例子:[1,2,3,4,5] 必须成为: [5,4,3,2,1]实现这一目标的最佳方法是什么?
3 回答
MMMHUHU
TA贡献1834条经验 获得超8个赞
为了得到阵列的反转副本,看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
白猪掌柜的
TA贡献1893条经验 获得超10个赞
如果您利用内置reverseObjectEnumerator
方法NSArray
和以下allObjects
方法,有一个更容易的解决方案NSEnumerator
:
NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];
allObjects
记录为返回一个数组,其中包含尚未遍历的对象nextObject
,按顺序:
此数组以枚举顺序包含枚举器的所有剩余对象。
守着一只汪
TA贡献1872条经验 获得超3个赞
一些基准
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.5x到2.5x之间:
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
速度在30x到40x之间(这里没有惊喜):
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]
在速度和轻松方面,明显的赢家也是如此。
- 3 回答
- 0 关注
- 1213 浏览
添加回答
举报
0/150
提交
取消