-1

I have an array with number of elements. I want to delete several elements in one step at different index (i.e I want to delete elements from index zero to index seven, at the same time I also want to delete elements from index 15 to index 21. Is this possible?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
codey
  • 21
  • 1
  • 6

4 Answers4

3

You can use an NSMutableIndexSet to contain the array indexes you want to remove.

Example:

Create an NSMutableIndexSet:

NSMutableIndexSet *indexes = [NSMutableIndexSet new];

Add the array indexes that you want to delete to it:

[indexes addIndex:3];
[indexes addIndexesInRange:NSMakeRange(5, 3)];

That will provide array indexes 3, 5, 6, 7

Remove the indexed item from the mutable array:

NSMutableArray *mutableArray = [array mutableCopy];
[mutableArray removeObjectsAtIndexes:indexes];

If needed: array = [mutableArray copy];

zaph
  • 111,848
  • 21
  • 189
  • 228
1

What about:

[array removeObjectsInRange:NSMakeRange(1, 10)];

or

[array removeObjectsAtIndexes:[NSIndexSet indexSetWithIndex:1]];

Find more information here and here.

Cesare
  • 9,139
  • 16
  • 78
  • 130
shudima
  • 460
  • 1
  • 5
  • 9
  • @shudima....can i add multiple ranges in this syntax using comma like [array removeObjectsInRange:<#(0-7),(15-21)#>] – codey Jan 26 '15 at 17:15
  • 1
    Not using these methods. I'm afraid you have to write something for yourself for this purpose. – shudima Jan 26 '15 at 17:18
0

You can use (void)removeObjectsAtIndexes:(NSIndexSet *)indexes of NSMutableArray

NSArray is not mutable, that is, you cannot modify it. You should take a look at NSMutableArray. Check out the "Removing Objects" section, you'll find there many functions that allow you to remove items:

Citated from: NSArray + remove item from array

Also see Removes the objects at the specified indexes from the array

Community
  • 1
  • 1
Jim Aho
  • 9,932
  • 15
  • 56
  • 87
  • `[anArray removeObjectsAtIndexes:` is handy, several methods return an `NSIndexSet`. – zaph Jan 26 '15 at 17:11
  • @Zaph..can i remove multiple elements using commas here like [anArray removeObjectsAtIndexes:0,1,2,3,5,10,17].. like this – codey Jan 26 '15 at 17:17
0

Have you looked at removeObjectsInRange:? Of course you'd have to call it however many times to delete multiple ranges in sequence but you could easily write a category function that can take care of it.

- (void)removeObjectsAtRanges:(NSMutableArray *)ranges {
    for range in ranges {
        [self removeObjectsInRange:range];
    }
}

Note: I haven't tested this in xcode but you get the general idea.

Edit: As was pointed out, once you delete a range, you'd have to dynamically shift all the other ranges so you don't go out of bounds.

barndog
  • 6,975
  • 8
  • 53
  • 105