简体   繁体   中英

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?

Correct answer without comments...

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

You can insert by "replacing" an empty range:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM