50

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.

2 Answers 2

111

Simply

[array insertObject:obj atIndex:0]; 

Check the documentation

Sign up to request clarification or add additional context in comments.

5 Comments

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.
If index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room.
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.
when you'll insertObject:obj atIndex:0 it will replace the object of 0th index, @Saphrosit am I right?
@NatureofOrigin no, if the position is occupied the existing objects are shifted, as Malloc said in its comment
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.