Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray - Add array at start

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?

like image 624
Adnan Avatar asked Mar 18 '14 22:03

Adnan


2 Answers

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];
like image 118
nhgrif Avatar answered Sep 22 '22 21:09

nhgrif


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

like image 24
Wain Avatar answered Sep 18 '22 21:09

Wain