Reputation: 2669
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!
Upvotes: 5
Views: 8756
Reputation: 8254
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];
Upvotes: 1
Reputation: 607
Swift:
let insetIndex = 3 // your any insert index
var array1 = ["1", "2", "3", "4", "5"]
let array2 = ["10", "11"]
array1.insert(contentsOf: array2, at: insetIndex)
OC:
int loc = 3; // your any insert index
NSMutableArray *array1 = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", nil];
NSMutableArray *array2 = [NSMutableArray arrayWithObjects:@"10", @"11", nil];
NSRange range = NSMakeRange(loc, array2.count); // NOTE: NSMakeRange(NSUInteger loc, NSUInteger len) len must be your array2.cout, or will crash with differs from count of index set
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
[array1 insertObjects:array2 atIndexes:indexSet];
output: ["1", "2", "3", "10", "11", "4", "5"]
Upvotes: 0
Reputation: 2669
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];
Upvotes: 14