Remove Every Other Element - objective-c

I have a large array (which I want to graph), and I want to reduce the size of it by removing every other element in it. If I have an array like:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"Hello", #"Again", #"World", #"I", #"Test", #"All-Day", nil];
How would I be able to get it down to:
(Hello, World, Test)

Any solution involving removeObjectAtIndex: is O(N^2), which you might not want since you said you “have a large array”.
#interface NSMutableArray (FG8_removeOddElements)
- (void)removeOddElements;
#end
#implementation NSMutableArray (FG8_removeOddElements)
- (void)removeOddElements {
// Given (a, b, c), result is (a, c), so round up.
NSUInteger finalCount = (self.count + 1) / 2;
// Element 0 never moves so start at 1.
for (NSUInteger i = 1; i < finalCount; ++i) {
self[i] = self[i * 2];
}
[self removeObjectsInRange:NSMakeRange(finalCount, self.count - finalCount)];
}
#end
Assuming removeObjectsInRange: is efficient, this performs the work in O(N) time.
UPDATE
Since HotLicks seems to think this algorithm doesn't work, here's a test:
#implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSMutableArray *array = #[#"a", #"b", #"c", #"d", #"e", #"f", #"g"].mutableCopy;
[array removeOddElements];
NSLog(#"%#", array);
}
#end
And here's the output:
2014-05-08 15:23:44.123 tester[43347:303] (
a,
c,
e,
g
)

Use a function like this:
- (NSMutableArray *)removeEveryOtherElement:(NSMutableArray *)array
{
NSLog(#"Input array: %#", array);
NSMutableArray *returnArray = [[NSMutableArray alloc] init];
for (int x = 0; x<=array.count - 1; x++) {
if (x % 2 == 0) { // if the index of the object is "even" (divisible by 2)
[returnArray addObject:[array objectAtIndex:x]];
}
}
NSLog(#"Returned array: %#", returnArray);
return returnArray;
}
You have to watch out, because if you're performing operations on an NSMutableArray the indices will change as you're adding and removing objects (thus the problem with my first answer).
Output:
2014-05-08 16:14:14.693 test[2013:303] Input array: (
0,
1,
2,
3,
4,
5
)
2014-05-08 16:14:14.693 test[2013:303] Returned array: (
0,
2,
4
)

Related

Selecting array elements using a binary pattern as the selector

I have an NSArray, and I've calculated a list of integers that represent (in binary) the elements I need to pull out of the array into a new array.
For example, I have 7, 11, and 13, whose bit patterns are 000111, 001011, and 001101. I want to grab three arrays, made of elements 0,1,2, then elements 0,1,3, and then 0,2,3 out of the main array.
Construct an NSIndexSet from the bit patterns you have:
#implementation NSIndexSet (NonContiguous)
+ (instancetype)indexSetFromMask:(NSUInteger)mask
{
NSMutableIndexSet * set = [NSMutableIndexSet indexSet];
for( NSUInteger i = 0; i < (sizeof(NSUInteger) * 8); i++ ){
if( mask & (1l << i) ){
[set addIndex:i];
}
}
return set;
}
#end
Then use objectsAtIndexes:
[origArray objectsAtIndexes:[NSIndexSet indexSetFromMask:7]];
// etc.
Assuming you want the output to be in the form [[a,b,c],[a,b,d],[a,c,d]] for the example, you could do something like this:
NSArray *sourceArray = [[NSArray alloc] initWithObjects:#"a",#"b",#"c",#"d",...,nil];
NSArray *grabArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:7],[NSNumber numberWithInt:11],[NSNumber numberWithInt:13],...,nil];
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
Then for each element of grabArray, add the correct elements to resultArray:
for (NSNumber num in grabArray) {
int n = [num intValue];
int bit = floor(log2(n)); //get highest bit in the current number
NSMutableArray *curr = [[NSMutableArray alloc] init];
while (n>0) {
if (n>pow(bit,2)) { //if this bit is a 1
[curr addObject:[sourceArray objectAtIndex:bit]];
}
n-=pow(bit,2);
bit-=1;
}
[resultArray addObject:curr];
}
Then resultArray should be the array you are looking for. It will add the objects in reverse order, so if order matters you would want to use [curr insertObject: [sourceArray objectAtIndex:bit] atIndex:0]; instead.

Reversing "columns" in a table made from a NSArray

I have a NSArray made out of numbers 1..50, which represents a table with columns & rows.
I need to reverse only the order of the columns, while keeping the order of the rows.
So for example:
0,1,2,3,4,5,6
7,8,9,9,10,11,12
has to be
6,5,4,3,2,1,0
12,11,10,9,8,7
Right now, i use a huge IF statement for that:
for (dd *d in dates[i]) {
if (tileNum==0) {
reversedTileNum = 6;
} else if (tileNum==1) {
reversedTileNum = 5;
}else if (tileNum==2) {
reversedTileNum = 4;
}else if (tileNum==3) {
reversedTileNum = 3;
}else if (tileNum==4) {
reversedTileNum = 2;
}else if (tileNum==5) {
reversedTileNum = 1;
} else if (tileNum==6) {
reversedTileNum = 0;
}
....
....
}
Here's a solution that should be easy to drop into any project. It involves two categories: one on NSMutableArray that provides a method to swap objects at two indices, and one on NSArray that provides the -arrayByReversingGroups: method. The idea is to swap the elements in pairs within a group, reversing the group. If number of elements in the array isn't an even multiple of groupSize, the extras at the end are left untouched.
The code presented here is a complete program, so you can see an example of using -arrayByReversingGroups: in the main() function.
#import <Foundation/Foundation.h>
#interface NSArray(Reversible)
-(NSArray*)arrayByReversingGroups:(int)groupSize;
#end
#interface NSMutableArray(Swappable)
-(void)swapObjectAtIndex:(int)first withObjectAtIndex:(int)second;
#end
#implementation NSArray(Reversible)
-(NSArray*)arrayByReversingGroups:(int)groupSize
{
NSMutableArray *newArray = [self mutableCopy];
// Iterate over the array in chunks of groupSize elements. i will be first index in
// the current chunk.
for (int i = 0; (i + groupSize) < [newArray count]; i += groupSize) {
// Iterate over the items in the current chunk, swapping the bth and
// (groupsize-b-1)th elements until they meet at groupsize/2.
for (int b = 0; b <= (groupSize / 2); b++) {
int first = i + b;
int second = i + groupSize - b - 1;
[newArray swapObjectAtIndex:first withObjectAtIndex:second];
}
}
return [newArray copy];
}
#end
#implementation NSMutableArray(Swappable)
-(void)swapObjectAtIndex:(int)first withObjectAtIndex:(int)second
{
id temp = [[self objectAtIndex:second] retain];
[self replaceObjectAtIndex:second withObject:[self objectAtIndex:first]];
[self replaceObjectAtIndex:first withObject:temp];
[temp release];
}
#end
int main (int argc, const char * argv[])
{
#autoreleasepool {
NSArray *array = [NSArray arrayWithObjects:
#"1", #"2", #"3", #"4", #"5", #"6", #"7", #"8", #"9", #"10", #"11", #"12", nil];
NSLog(#"Original: %#", array);
NSLog(#"Reversed: %#", [array arrayByReversingGroups:5]);
}
return 0;
}
I can give you the logic.. you will have to write the code...
First create a function where you pass in an array(here you will send in a row.) then in this function create a new tempeorary array and store all the values for that row in this column then overwrite the original array in reverse order from this new array and return this to the full matrix and store it in there ... hope it helps.

Get matched string from two NSArrays

How can I save the string that match from one NSArray with one index difference in NSMutableArray?
For example, there are three "apple", four "pineapple", six "banana", two "cocoa" and the rest of words dont have duplicate(s) in the nsarray, i would like to know if the nsarray has at least two same words. If yes, I would like to save "apple", "pineapple, "banana" and "cocoa" once in nsmutablearray. If there are other alike words, I would like to add them to namutablearray too.
My code (which still doesn't work properly);
NSArray *noWords = [[NSArray alloc] initWithArray:
[[NSString stringWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:#"words" ofType:#"txt"]
encoding:NSUTF8StringEncoding error:NULL]
componentsSeparatedByString:#"\n"]];
NSUInteger scount = [noWords count];
int ii = 0;
NSString *stringline;
for (ii; ii < scount; ii++)
{
stringline = [noWords objectAtIndex:ii];
NSLog(#"stringline : %# ", stringline);
}
int i = 1;
NSString *line;
for (i ; i < 10; i++)
{
line = [noWords objectAtIndex:i];
NSLog (#"line : %# ", line);
NSMutableArray *douwords = [NSMutableArray array];
if ([stringline isEqualToString:line])
{
NSString *newword;
for (newword in douwords)
{
[douwords addObject:newword];
NSLog (#"detected! %# ", douwords);
}
}
}
Here's a solution using two sets:
- (NSArray *)getDuplicates:(NSArray *)words
{
NSMutableSet *dups = [NSMutableSet set],
*seen = [NSMutableSet set];
for (NSString *word in words) {
if ([seen containsObject:word]) {
[dups addObject:word];
}
[seen addObject:word];
}
return [dups allObjects];
}
Assuming NSSet uses hash tables behind the scenes (which I'm betting it does), this is going to be faster than the previously suggested O(n^2) solution.
Here's something off the top of my head:
NSMutableSet* duplicates = [NSMutableSet set];
NSArray* words = [NSArray arrayWithObjects:#"Apple", #"Apple", #"Orange", #"Apple", #"Orange", #"Pear", nil];
[words enumerateObjectsUsingBlock:^(NSString* str, NSUInteger idx, BOOL *stop) {
for (int i = idx + 1; i < words.count; i++) {
if ([str isEqualToString:[words objectAtIndex:i]]) {
[duplicates addObject:str];
break;
}
}
}];
NSLog(#"Dups: %#", [duplicates allObjects]); // Prints "Apple" and "Orange"
The use of an NSSet, as opposed to an NSArray, ensures strings are not added more than once. Obviously, there are optimizations that could be done, but it should be a good starting point.
I assume that you want to count appearances of words in your array and output those with a count of more than one. A basic and verbose way to do that would be:
// Make an array of words - some duplicates
NSArray *wordList = [[NSArray alloc] initWithObjects:
#"Apple", #"Banana", #"Pencil",
#"Steve Jobs", #"Kandahar",
#"Apple", #"Banana", #"Apple",
#"Pear", #"Pear", nil];
// Make an mutable dictionary - the key will be a word from the list
// and the value will be a number representing the number of times the
// word appears in the original array. It starts off empty.
NSMutableDictionary *wordCount = [[NSMutableDictionary alloc] init];
// In turn, take each word in the word list...
for (NSString *s in wordList) {
int count = 1;
// If the word is already in the dictionary
if([wordCount objectForKey:s]) {
// Increse the count by one
count = [[wordCount objectForKey:s] intValue] + 1;
}
// Save the word count in the dictionary
[wordCount setObject:[NSNumber numberWithInt:count] forKey:s];
}
// For each word...
for (NSString *s in [wordCount keysOfEntriesPassingTest:
^(id key, id obj, BOOL *stop) {
if ([obj intValue] > 1) return YES; else return NO;
}]) {
// print the word and the final count
NSLog(#"%2d %#", [[wordCount objectForKey:s] intValue], s);
}
The output would be:
3 Apple
2 Pear
2 Banana

printing an array of arrays in objective C

Sorry for the simple question, but I am self taught and know that there are gaps in my education.
To print an array in objective C, I believe is:
NSLog(#"My array: %#", myArray);
How can I print an array of arrays?
Thanks
You want this:
for(NSArray *subArray in myArray) {
NSLog(#"Array in myArray: %#",subArray);
}
This will work for an array that has arrays nested one level deep.
You don't need to do anything different to log an array of arrays; the code exactly as you've written it will already show the contents of the sub-arrays.
That is, the following program:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *array = [NSMutableArray array];
for (int i=0; i<5; ++i) {
NSMutableArray *sub = [NSMutableArray array];
for (int j=0; j<=i; ++j) {
[sub addObject:[NSString stringWithFormat:#"%d", j]];
}
[array addObject:sub];
}
NSLog(#"Array: %#", array);
[pool drain];
return 0;
}
Produces the following output:
Array: (
(
0
),
(
0,
1
),
(
0,
1,
2
),
(
0,
1,
2,
3
),
(
0,
1,
2,
3,
4
)
)
Clearly, it's already logging the sub-arrays just fine. If you want to control the formatting differently, you'd have to manually iterate them, but by default, the -description of an NSArray is little more than the -description of every object in that array, which includes all sub-arrays.
So I was embarrassed by the recursiveDescription thing, so I wrote my own as a category on NSArray. Note that this code will print out a description for an array of arrays to any depth. The description itself could probably use a bit more formatting than commas and newlines. Here you go:
#interface NSArray (RecursiveDescription)
- (NSString *)recursiveDescription;
#end
#implementation NSArray (RecursiveDescription)
- (NSString *)recursiveDescription {
NSMutableString *description = [[NSMutableString alloc] initWithString:#"Array (\n"];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (NSObject *child in self) {
if ([child respondsToSelector:#selector(recursiveDescription)]) {
[description appendFormat:#"%#,\n", [child recursiveDescription]];
}
else {
[description appendFormat:#"%#,\n", [child description]];
}
}
[pool drain];
[description appendString:#"\n)"];
return [description autorelease];
}
#end
Try logging the return value from NSArray's -description method.
NSLog(#"My array: %#", [myArray description]);
Moreover, for print all of elements
int i = 0;
int j = 0;
for(NSArray *subArray in myArray) {
NSLog(#"[%d] %#",i, subArray);
j =0;
for(NSObject *element in subArray) {
NSLog(#"[%d:%d] %#", i,j,element);
++j;
}
++i;
}
As much as I like how easy it is to log out an object in Objective-C, I didn't like seeing a 2D array as a very long list. I created a category on NSArray that prints out 2D arrays. It's not perfect and can be improved, but it has worked for me.
Header:
#interface NSArray (Logging)
- (void)log2DArray;
#end
Implementation:
#import "NSArray+Logging.h"
#implementation NSArray (Logging)
- (void)log2DArray {
NSMutableString *formattedString = [[NSMutableString alloc] init];
NSInteger longestSubarrayLength = 0;
for (NSArray *subarray in self) {
if (subarray.count > longestSubarrayLength) {
longestSubarrayLength = subarray.count;
}
}
for (int i = 0; i < longestSubarrayLength; i++) {
[formattedString appendFormat:#"\n"];
for (int j = 0; j < self.count; j++) {
NSArray *tempArray = [self objectAtIndex:j];
if (tempArray.count <= longestSubarrayLength) {
[formattedString appendFormat:#"%#\t", [tempArray objectAtIndex:i]];
} else {
[formattedString appendFormat:#"\t"];
}
}
}
NSLog(#"%#", formattedString);
}
#end
Usage:
[myArray log2DArray];
Or use recursiveDescription :)
NSLog(#"my arrays: %#", [myArray recursiveDescription]);

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?
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.
For obtaining a reversed copy of an array, look at danielpunkass' solution using reverseObjectEnumerator.
For reversing a mutable array, you can add the following category to your code:
#implementation NSMutableArray (Reverse)
- (void)reverse {
if ([self count] <= 1)
return;
NSUInteger i = 0;
NSUInteger j = [self count] - 1;
while (i < j) {
[self exchangeObjectAtIndex:i
withObjectAtIndex:j];
i++;
j--;
}
}
#end
Some benchmarks
1. reverseObjectEnumerator allObjects
This is the fastest method:
NSArray *anArray = #[#"aa", #"ab", #"ac", #"ad", #"ae", #"af", #"ag",
#"ah", #"ai", #"aj", #"ak", #"al", #"am", #"an", #"ao", #"ap", #"aq", #"ar", #"as", #"at",
#"au", #"av", #"aw", #"ax", #"ay", #"az", #"ba", #"bb", #"bc", #"bd", #"bf", #"bg", #"bh",
#"bi", #"bj", #"bk", #"bl", #"bm", #"bn", #"bo", #"bp", #"bq", #"br", #"bs", #"bt", #"bu",
#"bv", #"bw", #"bx", #"by", #"bz", #"ca", #"cb", #"cc", #"cd", #"ce", #"cf", #"cg", #"ch",
#"ci", #"cj", #"ck", #"cl", #"cm", #"cn", #"co", #"cp", #"cq", #"cr", #"cs", #"ct", #"cu",
#"cv", #"cw", #"cx", #"cy", #"cz"];
NSDate *methodStart = [NSDate date];
NSArray *reversed = [[anArray reverseObjectEnumerator] allObjects];
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(#"executionTime = %f", executionTime);
Result: executionTime = 0.000026
2. Iterating over an reverseObjectEnumerator
This is between 1.5x and 2.5x slower:
NSDate *methodStart = [NSDate date];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[anArray count]];
NSEnumerator *enumerator = [anArray reverseObjectEnumerator];
for (id element in enumerator) {
[array addObject:element];
}
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(#"executionTime = %f", executionTime);
Result: executionTime = 0.000071
3. sortedArrayUsingComparator
This is between 30x and 40x slower (no surprises here):
NSDate *methodStart = [NSDate date];
NSArray *reversed = [anArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
return [anArray indexOfObject:obj1] < [anArray indexOfObject:obj2] ? NSOrderedDescending : NSOrderedAscending;
}];
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(#"executionTime = %f", executionTime);
Result: executionTime = 0.001100
So [[anArray reverseObjectEnumerator] allObjects] is the clear winner when it comes to speed and ease.
DasBoot has the right approach, but there are a few mistakes in his code. Here's a completely generic code snippet that will reverse any NSMutableArray in place:
/* Algorithm: swap the object N elements from the top with the object N
* elements from the bottom. Integer division will wrap down, leaving
* the middle element untouched if count is odd.
*/
for(int i = 0; i < [array count] / 2; i++) {
int j = [array count] - i - 1;
[array exchangeObjectAtIndex:i withObjectAtIndex:j];
}
You can wrap that in a C function, or for bonus points, use categories to add it to NSMutableArray. (In that case, 'array' would become 'self'.) You can also optimize it by assigning [array count] to a variable before the loop and using that variable, if you desire.
If you only have a regular NSArray, there's no way to reverse it in place, because NSArrays cannot be modified. But you can make a reversed copy:
NSMutableArray * copy = [NSMutableArray arrayWithCapacity:[array count]];
for(int i = 0; i < [array count]; i++) {
[copy addObject:[array objectAtIndex:[array count] - i - 1]];
}
Or use this little trick to do it in one line:
NSArray * copy = [[array reverseObjectEnumerator] allObjects];
If you just want to loop over an array backwards, you can use a for/in loop with [array reverseObjectEnumerator], but it's likely a bit more efficient to use -enumerateObjectsWithOptions:usingBlock::
[array enumerateObjectsWithOptions:NSEnumerationReverse
usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
// This is your loop body. Use the object in obj here.
// If you need the index, it's in idx.
// (This is the best feature of this method, IMHO.)
// Instead of using 'continue', use 'return'.
// Instead of using 'break', set '*stop = YES' and then 'return'.
// Making the surrounding method/block return is tricky and probably
// requires a '__block' variable.
// (This is the worst feature of this method, IMHO.)
}];
(Note: Substantially updated in 2014 with five more years of Foundation experience, a new Objective-C feature or two, and a couple tips from the comments.)
After reviewing the other's answers above and finding Matt Gallagher's discussion here
I propose this:
NSMutableArray * reverseArray = [NSMutableArray arrayWithCapacity:[myArray count]];
for (id element in [myArray reverseObjectEnumerator]) {
[reverseArray addObject:element];
}
As Matt observes:
In the above case, you may wonder if -[NSArray reverseObjectEnumerator] would be run on every iteration of the loop — potentially slowing down the code. <...>
Shortly thereafter, he answers thus:
<...> The "collection" expression is only evaluated once, when the for loop begins. This is the best case, since you can safely put an expensive function in the "collection" expression without impacting upon the per-iteration performance of the loop.
Georg Schölly's categories are very nice. However, for NSMutableArray, using NSUIntegers for the indices results in a crash when the array is empty. The correct code is:
#implementation NSMutableArray (Reverse)
- (void)reverse {
NSInteger i = 0;
NSInteger j = [self count] - 1;
while (i < j) {
[self exchangeObjectAtIndex:i
withObjectAtIndex:j];
i++;
j--;
}
}
#end
The most efficient way to enumerate an array in reverse:
Use enumerateObjectsWithOptions:NSEnumerationReverse usingBlock. Using #JohannesFahrenkrug's benchmark above, this completed 8x quicker than [[array reverseObjectEnumerator] allObjects];:
NSDate *methodStart = [NSDate date];
[anArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//
}];
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(#"executionTime = %f", executionTime);
NSMutableArray *objMyObject = [NSMutableArray arrayWithArray:[self reverseArray:objArrayToBeReversed]];
// Function reverseArray
-(NSArray *) reverseArray : (NSArray *) myArray {
return [[myArray reverseObjectEnumerator] allObjects];
}
Reverse array and looping through it:
[[[startArray reverseObjectEnumerator] allObjects] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
...
}];
To update this, in Swift it can be done easily with:
array.reverse()
As for me, have you considered how the array was populated in the first place? I was in the process of adding MANY objects to an array, and decided to insert each one at the beginning, pushing any existing objects up by one. Requires a mutable array, in this case.
NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithCapacity:1];
[myMutableArray insertObject:aNewObject atIndex:0];
Or the Scala-way:
-(NSArray *)reverse
{
if ( self.count < 2 )
return self;
else
return [[self.tail reverse] concat:[NSArray arrayWithObject:self.head]];
}
-(id)head
{
return self.firstObject;
}
-(NSArray *)tail
{
if ( self.count > 1 )
return [self subarrayWithRange:NSMakeRange(1, self.count - 1)];
else
return #[];
}
There is a easy way to do it.
NSArray *myArray = #[#"5",#"4",#"3",#"2",#"1"];
NSMutableArray *myNewArray = [[NSMutableArray alloc] init]; //this object is going to be your new array with inverse order.
for(int i=0; i<[myNewArray count]; i++){
[myNewArray insertObject:[myNewArray objectAtIndex:i] atIndex:0];
}
//other way to do it
for(NSString *eachValue in myArray){
[myNewArray insertObject:eachValue atIndex:0];
}
//in both cases your new array will look like this
NSLog(#"myNewArray: %#", myNewArray);
//[#"1",#"2",#"3",#"4",#"5"]
I hope this helps.
I don't know of any built in method.
But, coding by hand is not too difficult. Assuming the elements of the array you are dealing with are NSNumber objects of integer type, and 'arr' is the NSMutableArray that you want to reverse.
int n = [arr count];
for (int i=0; i<n/2; ++i) {
id c = [[arr objectAtIndex:i] retain];
[arr replaceObjectAtIndex:i withObject:[arr objectAtIndex:n-i-1]];
[arr replaceObjectAtIndex:n-i-1 withObject:c];
}
Since you start with a NSArray then you have to create the mutable array first with the contents of the original NSArray ('origArray').
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr setArray:origArray];
Edit: Fixed n -> n/2 in the loop count and changed NSNumber to the more generic id due to the suggestions in Brent's answer.
If all you want to do is iterate in reverse, try this:
// iterate backwards
nextIndex = (currentIndex == 0) ? [myArray count] - 1 : (currentIndex - 1) % [myArray count];
You can do the [myArrayCount] once and save it to a local variable (I think its expensive), but I’m also guessing that the compiler will pretty much do the same thing with the code as written above.
Swift 3 syntax :
let reversedArray = array.reversed()
Try this:
for (int i = 0; i < [arr count]; i++)
{
NSString *str1 = [arr objectAtIndex:[arr count]-1];
[arr insertObject:str1 atIndex:i];
[arr removeObjectAtIndex:[arr count]-1];
}
Here is a nice macro that will work for either NSMutableArray OR NSArray:
#define reverseArray(__theArray) {\
if ([__theArray isKindOfClass:[NSMutableArray class]]) {\
if ([(NSMutableArray *)__theArray count] > 1) {\
NSUInteger i = 0;\
NSUInteger j = [(NSMutableArray *)__theArray count]-1;\
while (i < j) {\
[(NSMutableArray *)__theArray exchangeObjectAtIndex:i\
withObjectAtIndex:j];\
i++;\
j--;\
}\
}\
} else if ([__theArray isKindOfClass:[NSArray class]]) {\
__theArray = [[NSArray alloc] initWithArray:[[(NSArray *)__theArray reverseObjectEnumerator] allObjects]];\
}\
}
To use just call: reverseArray(myArray);