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?
-
Not in one step. But if you iterate through the array backwards you can delete them all in one "pass". Or do the straight-forward forward loop and copy to a new array, omitting what you don't want. – Hot Licks Jan 26 '15 at 17:08
-
Are you using Swift or Objective-C? – Cesare Jan 26 '15 at 17:09
-
@HotLicks...thanks for the suggestion can you post some code regarding this how to solve this problem. – codey Jan 26 '15 at 17:11
-
objective c....xcode(iphone) – codey Jan 26 '15 at 17:11
4 Answers
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];

- 111,848
- 21
- 189
- 228
What about:
[array removeObjectsInRange:NSMakeRange(1, 10)];
or
[array removeObjectsAtIndexes:[NSIndexSet indexSetWithIndex:1]];
-
@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
-
1Not using these methods. I'm afraid you have to write something for yourself for this purpose. – shudima Jan 26 '15 at 17:18
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
-
`[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
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.

- 6,975
- 8
- 53
- 105