Sorted NSIndexSet of sub array of NSArray

713 views Asked by At

Let say I have NSIndexSet of array indexes. I want to sort this NSIndexSet depends on NSArray.

So, let say we have array :

array = @[1,4,3,8,6,2,9];

and index set

indexSet :  (2,4,5,6)

so "sub array" of this indexes would be

subArray = @[3,6,2,9]

So what I would like to have is :

I have :
indexSet : (2,4,5,6)
array = @[1,4,3,8,6,2,9];
return indexSet : (5,2,4,6) --> this are sorted indexes of "sub array".

How to achieve this?

1

There are 1 answers

0
Ken Thomases On BEST ANSWER

You can't achieve what you want. NSIndexSet doesn't maintain an order separate from the order of the indexes themselves. It is always in index order.

You could build an array of number objects which you treat as indexes.

NSArray* array = /* ... */;
NSMutableArray* indexes = [[NSMutableArray alloc] init];
[indexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop){
    [indexes addObject:@(idx)];
}];
[indexes sortUsingComparator:^NSComparisonResult(NSNumber* obj1, NSNumber* obj2){
    NSUInteger index1 = obj1.unsignedIntegerValue;
    NSUInteger index2 = obj2.unsignedIntegerValue;
    id element1 = array[index1];
    id element2 = array[index2];
    return [element1 compare:element2];
}];