I have an existing array to which I want to add another array at the beginning of the existing array.
Add to the end is not a problem with
[existingArray addObjectsFromArray:newArray];
But how to add it to the beginning?
You can do this without a temporary array and without assuming that newArray is an NSMutableArray and without creating an NSIndexSet :
newArray
NSMutableArray
NSIndexSet
[existingArray replaceObjectsInRange:NSMakeRange(0,0) withObjectsFromArray:newArray];
Same method, but invert the order and reassign:
[newArray addObjectsFromArray:existingArray]; existingArray = newArray;
Hope this helps you ... to love ...
You can create a third array and add elements in the order you want, and then return to the first:
NSMutableArray *tempArray = [NSMutableArray arrayWithArray:newArray]; [tempArray addObjectsFromArray:existingArray];
For completeness, here is a completely different way:
NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange: (NSRange) {0, [newArray count]}]; [existingArray insertObjects: newArray atIndexes: indexes];
You can try adding objects to the index below the code:
[existingArray insertObjects:newArray atIndexes:0];
Thanks!..
Think the first two answers are more elegant, but here's a different way:
Using:
[existingArray insertObjects:newArray atIndexes:indexSet];
where indexSet runs from 0 to newArray.count-1 .
indexSet
0
newArray.count-1
To insert jjust before existing array u must use index 0
[newArray insertObject: existingArray atIndex:0]