简体   繁体   English

反转10个最后的Objective-C数组对象?

[英]Reverse 10 last Objective-C Array objects?

I am using following code to reverse the objects in an array. 我正在使用以下代码来反转数组中的对象。 but this methods reverse all the objects in array. 但是此方法会反转数组中的所有对象。

NSArray* finalreversed = [[myArray reverseObjectEnumerator] allObjects];

How can I reverse only last 10 elements in array, ie myArray? 如何只反转数组中的最后10个元素,即myArray?

NSUInteger rangeLength = MIN(10, myArray.count);
NSUInteger rangeLocation = MAX(0, myArray.count - rangeLength);
NSArray *lastTenReversed = [[[myArray subarrayWithRange:NSMakeRange(rangeLocation, rangeLength)] reverseObjectEnumerator] allObjects];
NSArray *finalArray = [[myArray subarrayWithRange:NSMakeRange(0, rangeLocation)] arrayByAddingObjectsFromArray:lastTenReversed];

The MIN / MAX checks ensure that you don't go out of bounds. MIN / MAX检查可确保您不会超出范围。 If the array has less than 10 objects, it will simply reverse all of them. 如果数组的对象少于10个,它将简单地反转所有对象。

Split off the first (length-10) objects. 拆分第一个(长度为10)的对象。 Split off the last 10. Reverse the latter. 拆分出最后10个。逆转后者。 Concatenate the former with the reversed. 将前者与相反者串联在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM