I have a NSMutableArray and need objects [0:5] only. Is there a simple way to slice? Can I drop all objects after index? Can I copy a sub-array to another NSMutableArray?
Asked
Active
Viewed 1.6k times
21
-
3Thanks guys, I was looking at NSMutableArray and didn't see these in the reference. – Mar 13 '11 at 23:07
2 Answers
63
Use the instance method - (NSArray *)subarrayWithRange:(NSRange)range
.
For example:
NSArray* slicedArray = [wholeArray subarrayWithRange:NSMakeRange(0, 5)];

James Bedford
- 28,702
- 8
- 57
- 64
-
14Note that NSMakeRange(0,5) doesn't mean 'slice positions 0 to 5', it means 'take a slice starting at 0 and incrementing by 5'. It makes no difference with 0:5, but if you do 1:5 the distinction becomes important. – Rik Smith-Unna Aug 27 '12 at 11:08
-
4Yep, so using an `NSMakeRange(1, 5)` would mean that `slicedArray` would contain objects from `wholeArray` at indexes 1 to 6. – James Bedford Sep 04 '12 at 03:03
-
2To avoid `NSRangeException` for less than 5 elements you should use: `[wholeArray subarrayWithRange:NSMakeRange(0, MAX(wholeArray.count, 5))]` – Szu Jan 30 '15 at 09:43
-
2@Szu I think you'll find that we need `MIN` instead of `MAX` to prevent a crash :) – Max Chuquimia Jun 22 '15 at 05:51
-
@JamesBedford: actually `slicedArray` would contain objects from `wholeArray` at indexes 1 to 5, not 1 to 6. – xZenon Oct 04 '16 at 20:04
15
I see James Bedford already answered how to extract a range of indexes. To delete the objects in a range from an NSMutableArray, you can use [wholeArray removeObjectsInRange:...]
. To delete all objects after a particular index, you can create an appropriate range as NSMakeRange(index, wholeArray.count - index)
.

Anomie
- 92,546
- 13
- 126
- 145