gpt4 book ai didi

objective-c - NSArray 反向索引排序

转载 作者:行者123 更新时间:2023-11-28 18:04:16 27 4
gpt4 key购买 nike

这是我的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

有什么想法吗?

我也需要保持数组的原始排序顺序。

最佳答案

尝试调用 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];

关于objective-c - NSArray 反向索引排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11425396/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com