Merge two arrays while preserving the original array order

后端 未结 3 2036
轮回少年
轮回少年 2021-01-23 06:40

I\'ve writing an application that requests data from an external source (Twitter), which is returned as an ordered array in chronological order:

External array

相关标签:
3条回答
  • 2021-01-23 07:18

    You should use the array as a stack, so the old items get pushed below the newer ones. You could achieve that by adding every element at the last position using [myArray addObject:newObject];. You will have to iterate backwards in the original array in order to insert them from oldest to newest. You can achieve that by doing :

    for(NSUInteger index = [newArray count] - 1; i == 0; i--)
    {
        NSDictionary*object = [newArray objectAtIndex:index];
        [myArray addObject:object];
    }
    

    This way you will get the array you need

    Cheers

    0 讨论(0)
  • 2021-01-23 07:26

    Just use the new array as the first array and add the old items after.

    NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:externalArray.count + myArray.count];
    for(NSDictionary *item in externalArray) {
    
        // Need loop so I can do some extra stuff here with each item object (not shown in this example.)
        [newArray addObject: item];
    }
    
    [newArray addObjectsFromArray:myArray];
    
    0 讨论(0)
  • 2021-01-23 07:30
    NSArray *newArray = [externalArray arrayByAddingObjectsFromArray:myArray];
    [myArray release];
    myArray = [newArray mutableCopy];
    

    Any reason not to do this?

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