我須要扭轉個人NSArray
。 數組
舉個例子: spa
[1,2,3,4,5]
必須成爲: [5,4,3,2,1]
code
實現這一目標的最佳方法是什麼? 對象
試試這個: ci
for (int i = 0; i < [arr count]; i++) { NSString *str1 = [arr objectAtIndex:[arr count]-1]; [arr insertObject:str1 atIndex:i]; [arr removeObjectAtIndex:[arr count]-1]; }
至於我,您是否考慮過首先如何填充陣列? 我正在將MANY對象添加到數組中,並決定在開頭插入每一個對象,將任何現有對象向上推一個。 在這種狀況下,須要一個可變數組。 element
NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithCapacity:1]; [myMutableArray insertObject:aNewObject atIndex:0];
若是你想作的只是反向迭代,試試這個: rem
// iterate backwards nextIndex = (currentIndex == 0) ? [myArray count] - 1 : (currentIndex - 1) % [myArray count];
您能夠執行[myArrayCount]一次並將其保存到本地變量(我認爲它很昂貴),但我也猜想編譯器幾乎會對上面編寫的代碼作一樣的事情。 編譯器
NSMutableArray *objMyObject = [NSMutableArray arrayWithArray:[self reverseArray:objArrayToBeReversed]]; // Function reverseArray -(NSArray *) reverseArray : (NSArray *) myArray { return [[myArray reverseObjectEnumerator] allObjects]; }
一些基準 it
1. reverseObjectEnumerator allObjects io
這是最快的方法:
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]
在速度和輕鬆方面是明顯的贏家。