NSMutableArray add object with order

scorpiozj picture scorpiozj · Nov 18, 2011 · Viewed 18.2k times · Source

I have a NSMUtableArray which has elements, for example:

a,b,c,e

And I want to add an object d to behind c and before e. In other words, I'd like to insert an object to a sorted array.(The object can be a custom object, too)

I'd like to know : besides using for to find the position, is there any other method to implement it? It is better to use the iOS api.

Thanks.

Answer

user557219 picture user557219 · Nov 18, 2011

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.