NSMutableArray add object with order

Objective CNsmutablearraySorting

Objective C Problem Overview


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.

Objective C Solutions


Solution 1 - Objective C

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.

Solution 2 - Objective C

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

https://stackoverflow.com/questions/1363593/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

Solution 3 - Objective C

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:)];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionscorpiozjView Question on Stackoverflow
Solution 1 - Objective Cuser557219View Answer on Stackoverflow
Solution 2 - Objective CMarek SeberaView Answer on Stackoverflow
Solution 3 - Objective CNSResponderView Answer on Stackoverflow