0

这是我的NSArray

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

有什么想法吗?

我还需要将数组保持在原始排序顺序。

4

2 回答 2

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];
于 2012-07-11T04:11:41.003 回答
1

那或者改变你的循环

for(int i = size; i >= 1; i--) 
于 2012-07-11T04:28:25.877 回答