NSMutableArray - Add array at start

被刻印的时光 ゝ 提交于 2019-12-03 02:06:23

First, build an NSIndexSet.

NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:
    NSMakeRange(0,[newArray count])];

Now, make use of NSMutableArray's insertObjects:atIndexes:.

[oldArray insertObjects:newArray atIndexes:indexes];

Alternatively, there's this approach:

oldArray = [[newArray arrayByAddingObjectsFromArray:oldArray] mutableCopy];

NSMutableArray offers the insertObjects:atIndexes: method, but it's easier to append the way you suggest using addObjectsFromArray:.

-insertObject:atIndexes: is easy enough, and should (I believe) be more efficient than using -addObjects and swapping arrays. It'd probably end up looking something like this:

[existingResults addObjects:newResults atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, newResults.count)]]`

Creating a new array is probably your best solution, but you can also use a loop

NSUInteger index;

index = 0;
for ( id item in sourceArray )
{
    [destArray insertObject:item atIndex:index];
    index++;
}
Nghia Luong

Just simple way:

NSMutableArray *arrayTmp = [firstArr addObjectsFromArray:myArray];
myArray = arrayTmp;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!