how to add new elements in array at the top of the table view

ぐ巨炮叔叔 提交于 2019-12-04 18:36:30

Insert the new items at the top of your array using NSMutableArray insertObject: atIndex:.

Create a new array with a capacity of the old array + n new objects. Add the new objects, then loop through the previous array and copy that into the new array. This way the first index - n-1 will have the items you added, therefore being displayed at the top of the table.

There may be an easier way to do this, but this implementation will definitely work.

Do you use arrayByAddingObjectsFromArray: to add new elements?

If so, the objects are added to the end of the original array, and thus displayed at the end of the table view.

So instead of adding new array to the end of the old array, how about adding old array to the end of the new array?

self.arrayForTable = [arrayWithNewElements arrayByAddingObjectsFromArray:arrayForTable];

If you are using NSMutableArray so there are many function available for inserting the new element at your desire place in array and they are ....

Inserts a given object into the array's contents at a given index.

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index

Inserts the objects in in a given array into the receiving array at the specified indexes.

- (void)insertObjects:(NSArray *)objects atIndexes:(NSIndexSet *)indexes

Below is the code from Apple Documentation ...

NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"two", @"three", @"four", nil];
NSArray *newAdditions = [NSArray arrayWithObjects: @"a", @"b", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];    
[array insertObjects:newAdditions atIndexes:indexes];
NSLog(@"array: %@", array);
// Output: array: (one, a, two, b, three, four)

In the use case where you have an array of entities that need to be populated at that beginning of your existing data source, try the following:

-(NSMutableArray*)returnReorganizedArrayWithEarlierEntities:(NSArray*)theEarlierEntities{
    theEarlierEntities = [[theEarlierEntities reverseObjectEnumerator] allObjects];
    for(int i = 0; i < [theEarlierEntities count]; i++)
        [dataSourceArray insertObject:[theEarlierEntities objectAtIndex:i] atIndex:0];
    return dataSourceArray;
}

What this method does is reverse the order of the new entities you want added so that they are placed correctly (bottom-up) at the beginning of your existing data structure.

Cheers!

If you still want to use Array you can do this: imagine we have an array whose type is your model(struct to class).

var yourArray = [YourModel]()

to add a new element on top of the array you can use

yourArray.insert(newElemet: Model, at: 0)

refer to this thread: Add an element to an array in Swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!