NSMutableArray - Add array at start

后端 未结 5 1493
逝去的感伤
逝去的感伤 2021-02-05 12:47

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 a

相关标签:
5条回答
  • 2021-02-05 13:31

    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++;
    }
    
    0 讨论(0)
  • 2021-02-05 13:33

    Just simple way:

    NSMutableArray *arrayTmp = [firstArr addObjectsFromArray:myArray];
    myArray = arrayTmp;
    
    0 讨论(0)
  • 2021-02-05 13:35

    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];
    
    0 讨论(0)
  • 2021-02-05 13:40

    -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)]]`
    
    0 讨论(0)
  • 2021-02-05 13:45

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

    0 讨论(0)
提交回复
热议问题