7

I have an existing array to which i want to add an other array in the front of the existing array.

Add to the end is no problem with

[existingArray addObjectsFromArray:newArray];

But how to add it to the front?

8 Answers 8

19

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

[existingArray replaceObjectsInRange:NSMakeRange(0,0)
                withObjectsFromArray:newArray];
Sign up to request clarification or add additional context in comments.

1 Comment

Nice and elegant solution.
16

Same method, but invert the order and re-assign:

[newArray addObjectsFromArray:existingArray];
existingArray = newArray;

Comments

3
 [newArray addObjectsFromArray:existingArray];
 existingArray = newArray;

Hope,this will help you..enjoy...

Comments

2

You can create a 3rd array and add the elements in the order you want, then asing it back to the first one:

NSMutableArray *tempArray = [NSMutableArray arrayWithArray:newArray];
[tempArray addObjectsFromArray:existingArray];

Comments

2

For completeness' sake here's a very different way:

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

Comments

0

You can try add objects to index below code:

[existingArray insertObjects:newArray atIndexes:0];

Thanks..!

1 Comment

U will get error [NSMutableArray insertObjects:atIndexes:]: index set cannot be nil
0

Think the two first answers are more elegant, but here's another way:

Use:

[existingArray insertObjects:newArray atIndexes:indexSet];

where the indexSet runs from 0 to newArray.count-1 .

Comments

-2

To insert jjust before the existing array u must use index 0

[newArray insertObject: existingArray atIndex:0]

1 Comment

that whole insert the whole array at index 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.