Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple NSArray - Bring object to to front NSArray

Simple question for NSarray. I have objects stored in an NSMuteableArray. [obj1, obj2, obj3]

If an object is chosen, I want to bring this to the front of the array. I.e. if obj3 is chosen, then:

[obj3, obj1, obj2]

Will the below work or duplicate obj3? Also, can this be made thread safe?

[myMutableArray insertObject:obj3 atIndex:0];
like image 478
DaynaJuliana Avatar asked Jul 16 '26 08:07

DaynaJuliana


2 Answers

Assuming you need to preserve the order of the other elements, you need to remove and then insert the object in question:

NSMutableArray *array = ... // array with objects
NSInteger index = ... // index of object to move to the front
id obj = array[index];
[array removeObjectAtIndex:index];
[array insertObject:obj atIndex:0];
like image 189
rmaddy Avatar answered Jul 17 '26 20:07

rmaddy


Your code will insert another reference to obj3 at the front of the array (ie. the array will now contain 4 elements) but it won't actually duplicate the object.

You need to use exchangeObjectAtIndex:withObjectAtIndex -

[myMutableArray exchangeObjectAtIndex:0 withObjectAtIndex:selectedIndex]

where selectedIndex is the index of the object that was selected.

NSMutableArray is not thread safe, so you will need to wrap @synchronizsed(myMutableArray) around accesses to this array if you are potentially modifying it from multiple threads or modifying it while another thread is iterating it.

If you want to retain the order of the array beyond the first element then you will need to perform a separate delete and insert operation -

id someObject=myMutableArray[selectedIndex];
[myMutableArray removeObjectAtIndex:selectedIndex];
[myMutableArray insertObject:someObject atIndex:0]; 
like image 39
Paulw11 Avatar answered Jul 17 '26 21:07

Paulw11