1

I've tried using

NSMutableArray *existingArray = [@[@"1", @"3", @"4"] mutableCopy];
NSArray *newItems = @[@"2", @"2", @"2", @"2"];
[existingArray insertObjects:newItems atIndexes:[NSIndexSet indexSetWithIndex:1]];

Above code ends up crashing because i'm suppose to provide all indexes for all new items.

What i want is to be able to insert newItems at position 1 of existingArray preserving the order of newItems in final array too.

Is there an easy way to provide all those indexes?

2 Answers 2

2

Correct answer without comments...

NSInteger position = 1;
NSRange range = NSMakeRange(position, newItems.count);
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
[existingArray insertObjects:newItems atIndexes:indexSet];
Sign up to request clarification or add additional context in comments.

2 Comments

this will just add new items on top of the array. You should change the first value of NSMakeRange from 0 to 1 following the example in question.
@ZeeshanTufail thanks for remark. The answer was edited.
1

You can insert by "replacing" an empty range:

[existingArray replaceObjectsInRange:NSMakeRange(1, 0) withObjectsFromArray:newItems];

Comments

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.