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.
The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .
The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.
In general, the collection classes (for example, NSMutableArray , NSMutableDictionary ) are not thread-safe when mutations are concerned. That is, if one or more threads are changing the same array, problems can occur.
Simply
[array insertObject:obj atIndex:0];
Check the documentation
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With