Phi*_*ord 0 sorting objective-c nsarray ios
这是我的 NSArray
myArray = [NSArray arrayWithObjects: @"a", @"b", @"c", @"d", @"e", nil];
Run Code Online (Sandbox Code Playgroud)
现在我像这样循环遍历数组:
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
}
Run Code Online (Sandbox Code Playgroud)
在for循环中,这给了我订单:
a, b, c, d, e
Run Code Online (Sandbox Code Playgroud)
但我希望对数组进行排序以获得此顺序:
e, d, c, b, a
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
我需要将数组保持在原始排序顺序中.
尝试调用reverseObjectEnumerator数组并使用for-in循环遍历对象:
NSArray *myArray = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
// Interate through array backwards:
for (NSString *buttonTitle in [myArray reverseObjectEnumerator]) {
NSLog(@"%@", buttonTitle);
}
Run Code Online (Sandbox Code Playgroud)
这将输出:
c
b
a
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望通过索引遍历数组或使用它执行其他操作,则可以将数组反转到位:
NSArray *reversedArray = [[myArray reverseObjectEnumerator] allObjects];
Run Code Online (Sandbox Code Playgroud)