NSMutableArray add object with order

I have an NSMUtableArray that has elements, for example:

 a, b, c, e

And I want to add the object d to the end of c and to e . In other words, I would like to insert an object into a sorted array. (An object can also be a custom object)

I would like to know: besides using for to find a position, is there any other way to implement it? Better use iOS api.

Thank.

+50
sorting objective-c nsmutablearray
Nov 18 '11 at 9:14
source share
3 answers

You can use -[NSArray indexOfObject:inSortedRange:options:usingComparator:] to query NSArray for the index into which the object should be inserted, given the range of arrays that are currently sorted.

For example, if 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 of the array.

A comparator is a block object that receives two objects of type id and returns the value NSComparisonResult .

+106
Nov 18 '11 at 9:35
source share

To enter an item at a 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 the position of the object previously placed in NSMutableArray, use

 - (int)indexOfObject:(id)anObject 

NSMutableArray - Get an array of array indices by searching using a string

Section Search for objects in an array
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html

+3
Nov 18 '11 at 9:24 a.m.
source share

I would just add a new object at both ends and sort the array again. If the array you are adding to is already sorted, re-sorting that moves one object will be about as fast as anything you implement yourself.

 NSMutableArray *things; // populated id newObject; ... [things addObject:newObject atIndex:0]; [things sortUsingSelector:@selector(compare:)]; 
+3
Nov 18 '11 at 10:43
source share



All Articles