How to insert object in between the array?

13,303

Solution 1

[array insertObject:@"2" atIndex:1];

Solution 2

NSMutableArray *array = [[NSMutableArray alloc]init];
[array addObject:@"1"];
[array addObject:@"3"];
[array addObject:@"4"];
[array addObject:@"5"];

NSLog@"array is - %@", array);
[array addObject:@"2"];
[array sortUsingSelector:@selector(compare:)];
NSLog@"array is - %@", array);

Solution 3

There are multiple methods to add object in an Array Like

  1. If you are adding objects from array

    NSMutableArray *array = [[NSMutableArray alloc]initWithArray:sourceArray];
    [array addObjectsFromArray:sourceArray];
    
  2. If you want to add only single object

    [array addObject:object];
    
  3. If you want to add at some self defined index

    [array insertObject:object  atIndex:5];
    
  4. If you want to add by replacing other object

    [array replaceObjectAtIndex:5 withObject:object];
    

    And yes we can only add or remove from array if and only if it is Mutable.

Solution 4

[arrMutableArray insertObject:@"2" atIndex:1];

Solution 5

Array has method name is

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

Use such like

[myArrayName insertObject:@"My Object" atIndex:IndexNumber]; // Here put your object with number of index as you want.

Description:

Inserts the objects in the provided array into the receiving array at the specified indexes.

Parameters

=> objects
An array of objects to insert into the receiving array.
=> indexes
The indexes at which the objects in objects should be inserted. The count of locations in indexes must equal the count of objects. For more details, see the Discussion.

Discussion
Each object in objects is inserted into the receiving array in turn at the corresponding location specified in indexes after earlier insertions have been made. The implementation is conceptually similar to that illustrated in the following example.

Above explanation take from Apple's official documents.

Share:
13,303
Rohan
Author by

Rohan

iOS and Mac apps developer. Team Lead of Mobile Team.

Updated on June 04, 2022

Comments

  • Rohan
    Rohan almost 2 years

    I want to insert an object in between the array.

    For Example ;

     NSMutableArray *array = [[NSMutableArray alloc]init];
     [array addObject:@"1"];
     [array addObject:@"3"];
     [array addObject:@"4"];
     [array addObject:@"5"];
    
     NSLog@"array is - %@", array);
    

    Output will be -

    array is - { 1,3,4,5}

    But now i want to add another object as "2" in between this array and want the output like this ;

    array is - { 1,2,3,4,5}

    How can i do this?

    I have searched but could not find the solution.

    Please help me.

    Thanks.

  • Manthan
    Manthan over 10 years
    Take NSMutablearray for that.