Add an object to the beginning of an NSMutableArray?

27,948

Solution 1

Simply

[array insertObject:obj atIndex:0];

Check the documentation

Solution 2

As other answers have noted just use the insertObject:atIndex method. It is efficient as NSArrays do not necessarily consist of contiguous memory i.e. the elements don't always get moved when the insert happens especially for large arrays i.e. several hundred of thousand elements. See this blog Also note that in objective C only pointers are moved in the array so memmove can be used internally unlike C++ where copies have to be made.

Also this SE question.

Share:
27,948

Related videos on Youtube

gurooj
Author by

gurooj

iOS Engineer living in the Bay Area

Updated on July 09, 2022

Comments

  • gurooj
    gurooj almost 2 years

    Is there an efficient way to add an object to start of an NSMutableArray? I am looking for a good double ended queue in objective C would work as well.

  • EmptyStack
    EmptyStack over 12 years
    Few things to consider while using this method. If the array is empty, you can insert object at index 0 only. So, if the array contains 5 objects, you can insert object at 5th index. Trying to insert value at index 6 would result in exception.
  • Malloc
    Malloc about 11 years
    If index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room.
  • Supertecnoboff
    Supertecnoboff about 9 years
    Thank you so much for this. I am a beginner and I was thinking of making a for loop to do all this for me..... oh lord....... This is immeasurably easier.
  • Vijay Sanghavi
    Vijay Sanghavi about 8 years
    when you'll insertObject:obj atIndex:0 it will replace the object of 0th index, @Saphrosit am I right?
  • Manlio
    Manlio about 8 years
    @NatureofOrigin no, if the position is occupied the existing objects are shifted, as Malloc said in its comment