16

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.

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?

Adnan
  • 5,025
  • 5
  • 25
  • 44

5 Answers5

59

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];
nhgrif
  • 61,578
  • 25
  • 134
  • 173
2

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

Wain
  • 118,658
  • 15
  • 128
  • 151
1

-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)]]`
Siobhán
  • 1,451
  • 10
  • 9
1

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++;
}
user3386109
  • 34,287
  • 7
  • 49
  • 68
0

Just simple way:

NSMutableArray *arrayTmp = [firstArr addObjectsFromArray:myArray];
myArray = arrayTmp;
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
Nghia Luong
  • 790
  • 1
  • 6
  • 11