2

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?

Pat_Morita
  • 2,883
  • 3
  • 18
  • 30
  • `NSMutableIndexSet *indexSetToRemove = [[NSMutableIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, [array count])] [indexSetToRemove removeIndexes:indexSetToKeep]; [array removeObjectsAtIndexes:indexSetToRemove];` ? – Larme May 11 '17 at 10:03

3 Answers3

1

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];
Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
0

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];
vadian
  • 232,468
  • 27
  • 273
  • 287
0

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

dymv
  • 3,242
  • 2
  • 17
  • 29