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.
Related videos on Youtube
Comments
-
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 inobjective C
would work as well. -
EmptyStack over 12 yearsFew 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 about 11 yearsIf index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room.
-
Supertecnoboff about 9 yearsThank 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 about 8 yearswhen you'll
insertObject:obj atIndex:0
it will replace the object of 0th index, @Saphrosit am I right? -
Manlio about 8 years@NatureofOrigin no, if the position is occupied the existing objects are shifted, as Malloc said in its comment