Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an object to the beginning of an NSMutableArray?

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.

like image 268
gurooj Avatar asked Sep 03 '11 10:09

gurooj


People also ask

What is NSMutableArray Objective C?

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 .

What is difference between NSArray and NSMutableArray?

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.

Is NSMutableArray thread safe?

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.


2 Answers

Simply

[array insertObject:obj atIndex:0]; 

Check the documentation

like image 51
Manlio Avatar answered Oct 08 '22 10:10

Manlio


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.

like image 43
mmmmmm Avatar answered Oct 08 '22 11:10

mmmmmm