2012-07-11 49 views
0

這裏是我的NSArrayNSArray的反向索引排序

myArray = [NSArray arrayWithObjects: @"a", @"b", @"c", @"d", @"e", nil]; 

現在我循環遍歷數組是這樣的:

int size = [myArray count]; 
NSLog(@"there are %d objects in the myArray", size); 

for(int i = 1; i <= size; i++) { 
    NSString * buttonTitle = [myArray objectAtIndex:i]; 
    // This gives me the order a, b, c, d, e 
    // but I'm looking to sort the array to get this order 
    // e,d,c,b,a 

    // Other operation use the i int value so i-- doesn't fit my needs 
} 

在for循環這給了我的順序:

a, b, c, d, e 

但我期待排序數組以獲得此訂單:

e, d, c, b, a 

有什麼想法?

我需要保持原始排序順序的數組。

回答

8

嘗試調用陣列上reverseObjectEnumerator和使用for-in循環來循環通過的對象:

NSArray *myArray = [NSArray arrayWithObjects:@"a", @"b", @"c", nil]; 

// Interate through array backwards: 
for (NSString *buttonTitle in [myArray reverseObjectEnumerator]) { 
    NSLog(@"%@", buttonTitle); 
} 

這將輸出:

c 
b 
a 

或者,可以反轉代替陣列如果您想通過索引來遍歷數組或使用它進行其他操作:

NSArray *reversedArray = [[myArray reverseObjectEnumerator] allObjects]; 
+0

我認爲這是我正在尋找,仍然要測試,但這看起來像它。十分感謝! – 2012-07-11 04:15:43

+2

您可以直接在'reverseObjectEnumerator'上使用'for'循環。可能沒有理由使用'allObjects'來創建一個新的數組。只要做'for(NSString * buttonTitle in myArray.reverseObjectEnumerator)...'。 – 2012-07-11 04:39:49

1

這或改變你的循環

for(int i = size; i >= 1; i--)