The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...
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.
Overview. 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 .
You can use -[NSArray indexOfObject:inSortedRange:options:usingComparator:]
to ask an NSArray for the index where an object should be inserted given an array range that’s currently sorted.
For example, assuming the entire array is sorted::
NSMutableArray *array = …;
id newObject = …;
NSComparator comparator = …;
NSUInteger newIndex = [array indexOfObject:newObject
inSortedRange:(NSRange){0, [array count]}
options:NSBinarySearchingInsertionIndex
usingComparator:comparator];
[array insertObject:newObject atIndex:newIndex];
Since this method uses binary search, it is more efficient than iterating over all elements in the array.
The comparator is a block object that receives two objects of type id
and returns an NSComparisonResult
value.
To inject element to known index (position) use
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html
And to find position of object previously placed into NSMutableArray use
- (int)indexOfObject:(id)anObject
NSMutableArray - Get Arrays Index Integer By Searching With A String
Section Finding Objects in an Array
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html
I'd just add the new object at either end and sort the array again. If the array you're adding to is already sorted, the re-sort that moves one object is going to be about as quick as anything you'd implement yourself.
NSMutableArray *things; // populated
id newObject;
...
[things addObject:newObject atIndex:0];
[things sortUsingSelector:@selector(compare:)];
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