Ios add an array to the array in front

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?

+7
source share
8 answers

You can do this without a temporary array and without assuming that newArray is an NSMutableArray and without creating an NSIndexSet :

 [existingArray replaceObjectsInRange:NSMakeRange(0,0) withObjectsFromArray:newArray]; 
+19
source

Same method, but invert the order and reassign:

 [newArray addObjectsFromArray:existingArray]; existingArray = newArray; 
+16
source
  [newArray addObjectsFromArray:existingArray]; existingArray = newArray; 

Hope this helps you ... to love ...

+3
source

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]; 
+2
source

For completeness, here is a completely different way:

 NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange: (NSRange) {0, [newArray count]}]; [existingArray insertObjects: newArray atIndexes: indexes]; 
+2
source

You can try adding objects to the index below the code:

 [existingArray insertObjects:newArray atIndexes:0]; 

Thanks!..

0
source

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 .

0
source

To insert jjust before existing array u must use index 0

 [newArray insertObject: existingArray atIndex:0] 
-2
source

All Articles