Zeeshan Tufail
Zeeshan Tufail

Reputation: 33

How to insert an array into an existing NSMutableArray at a specific index

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?

Upvotes: 1

Views: 40

Answers (2)

kirander
kirander

Reputation: 2256

Correct answer without comments...

NSInteger position = 1;
NSRange range = NSMakeRange(position, newItems.count);
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
[existingArray insertObjects:newItems atIndexes:indexSet];

Upvotes: 2

Ken Thomases
Ken Thomases

Reputation: 90531

You can insert by "replacing" an empty range:

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

Upvotes: 1

Related Questions