Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reverse a NSArray in Objective-C?

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?

like image 443
Andy Jacobs Avatar asked Feb 25 '09 15:02

Andy Jacobs


People also ask

How do you reverse an NSArray?

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.

What is NSArray Objective C?

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.

Is NSArray ordered?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

Can NSArray contain nil?

arrays can't contain nil.


1 Answers

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.

like image 69
danielpunkass Avatar answered Sep 18 '22 23:09

danielpunkass