NSMutableArray keep objects at indexSet

438 Views Asked by At

I am on Xcode 8.2, OSX not iOS, Objective-C

I have an NSMutableArray and an NSIndexSet. I want to remove ALL items of the array EXCEPT those at the NSIndexSet. So basically something like

[array keepObjectsAtIndexes:indexSet]; // just to carify i know this doesnt exist

What's the best way to do this? Can i somehow 'reverse' the index set?

3

There are 3 best solutions below

0
dymv On BEST ANSWER

You can do this even without creating unnecessary arrays:

// Initial array
NSMutableArray* array = [[NSMutableArray alloc] initWithArray:@[@"one", @"two", @"three", @"four", @"five"]];

// Indices we want to keep
NSIndexSet* indexSet = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(1, 3)];

// Preparing reversed index set
NSMutableIndexSet *indexSetToRemove = [[NSMutableIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, [array count])];
[indexSetToRemove removeIndexes:indexSet];

// Removing objects from that set
[array removeObjectsAtIndexes:indexSetToRemove];

The output will be:

2017-05-11 20:10:22.317 Untitled 15[46504:32887351] (
    two,
    three,
    four
)

Cheers

0
vadian On

You could get the objects with objectsAtIndexes and replace the entire objects with the result.

NSArray *temp = [array objectsAtIndexes:indexSet];
[array replaceObjectsInRange:NSMakeRange(0, array.count) withObjectsFromArray: temp];
0
Sergey Kalinichenko On

You can construct an inverse of a given NSIndexSet by constructing an index set that has all indexes in range 0..arrayCount-1, inclusive, and then removing the indexes in your indexSet from it:

NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet initWithIndexesInRange:NSMakeRange(0, array.count)];
[indexesToRemove removeIndexes:indexesToKeep];
[array removeObjectsAtIndexes:indexesToRemove];