Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Objects from one Array to Another at a Specific Position

I have two Mutable Arrays, firstArray and secondArray. Both are populated with objects. I want to add the objects from secondArray to firstArray at a specific point (not at the end and not at the beginning) in the firstArray. Is there a way to do this? Currently I'm only using this line of code:

[self.firstArray addObjectsFromArray:secondArray];

What I want is FOO CODE: self.firstArray addObjectFromArray AT SPECIFIC POINT X: secondArray,specificpointX)

Any help is appreciated!

like image 278
Lauren Quantrell Avatar asked Mar 03 '11 17:03

Lauren Quantrell


2 Answers

Answering my own question, this works:

 int z;
 z = (int)self.specificPosition;

 // Start adding at index position z and secondArray has count items

 NSRange range = NSMakeRange(z, [secondArray count]);     
 NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
 [self.firstArray insertObjects:secondArray atIndexes:indexSet];
like image 146
Lauren Quantrell Avatar answered Oct 20 '22 01:10

Lauren Quantrell


Check out the documentation for NSMutableArray.

You just need to use the insertObject:AtIndex: function.

I've listed a simple example below where I create an array of size 10 and add an object at index 5.

NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:10];
[myArray insertObject:@"Hello World" AtIndex:5];

I hope this helps.

like image 21
Nick Cartwright Avatar answered Oct 20 '22 00:10

Nick Cartwright