NSMutableArray - 在开始时添加数组

问题描述:

这是一个简单的下拉刷新案例.我已将数据加载到表中,并在后端有一个可变数据数组,我收到一个新数据数组,并希望在现有数组的开头添加这个完整数组.

It is a simple pull to refresh case. I have data loaded into table and have a mutable data array at back-end, I receive a array of new data and want to add this complete array at start of existing array.

一种解决方法是使用新到达的数据创建新数组,然后使用 addObjectsFromArray: 方法将以前的数组添加到其中.是否有一些解决方法可以将新数据数组直接添加到前一个数组的开头?

One workaround is to create new array with new arrived data and then add previous array into it using addObjectsFromArray: method. Is there some workaround to add new data array to the start of previous array directly?

首先,构建一个 NSIndexSet.

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

现在,使用 NSMutableArrayinsertObjects:atIndexes:.

[oldArray insertObjects:newArray atIndexes:indexes];

或者,有这种方法:


Alternatively, there's this approach:

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