简体   繁体   中英

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?

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. If the array has less than 10 objects, it will simply reverse all of them.

Split off the first (length-10) objects. Split off the last 10. Reverse the latter. Concatenate the former with the reversed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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