47

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.

Sandy
  • 4,714
  • 4
  • 42
  • 69
gurooj
  • 2,060
  • 4
  • 21
  • 25

2 Answers2

104

Simply

[array insertObject:obj atIndex:0];

Check the documentation

Manlio
  • 10,328
  • 9
  • 44
  • 76
  • 3
    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. – EmptyStack Sep 03 '11 at 10:45
  • 40
    If index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room. – Malloc Feb 21 '13 at 21:56
  • 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. – Supertecnoboff Feb 18 '15 at 21:44
  • when you'll `insertObject:obj atIndex:0` it will replace the object of 0th index, @Saphrosit am I right? – Vijay Sanghavi Apr 06 '16 at 09:52
  • 1
    @NatureofOrigin no, if the position is occupied the existing objects are shifted, as Malloc said in its comment – Manlio Apr 06 '16 at 10:15
5

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.

Community
  • 1
  • 1
mmmmmm
  • 30,723
  • 26
  • 85
  • 109