I need to reverse my NSArray
.
As an example:
[1,2,3,4,5]
must become: [5,4,3,2,1]
What is the best way to achieve this?
You can reverse a NSArray by writing your own loop iterating from the end towards the beginning and using a second array to add the items in reverse order. Or you can simply use - (NSEnumerator *)reverseObjectEnumerator from the NSArray class.
NSArray is Objective-C's general-purpose array type. It represents an ordered collection of objects. NSArray is immutable, so we cannot dynamically add or remove items. Its mutable counterpart, NSMutableArray, will be discussed in the second part of this tutorial.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
arrays can't contain nil.
There is a much easier solution, if you take advantage of the built-in reverseObjectEnumerator
method on NSArray
, and the allObjects
method of NSEnumerator
:
NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];
allObjects
is documented as returning an array with the objects that have not yet been traversed with nextObject
, in order:
This array contains all the remaining objects of the enumerator in enumerated order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With