How to get the first X elements of unknown size NSArray?

In lens C, I have an NSArray, call it NSArray* largeArray , and I want to get a new NSArray* smallArray with only the first x objects

... OR in case bigArray already has size <= x, I just want to get a copy of a large array. So, truncating any objects after index x.

This approach:

 NSArray *smallArray = [largeArray subarrayWithRange:NSMakeRange(0, x)]; 

Was there an answer to this very similar question . But with an error, an error occurs if largeArray is already small.

+10
objective-c
Jul 29 '13 at 16:14
source share
3 answers

You can do it...

 NSArray *smallArray = [largeArray subarrayWithRange:NSMakeRange(0, MIN(x, largeArray.count))]; 

This will take the first elements of x or the full array if it is less than x.

If largeArray.count is 100.

If x = 110, then it will accept the first 100 results. If x = 90, then it will take the first 90 results.

Yes it works: D

+25
Jul 29 '13 at 16:17
source share

Fogmeister's answer is perfectly good, but in situations where the array is often already small enough, this answer will be mildly inefficient as it always makes a copy. Here is a more efficient version:

 NSAarray *smallArray = largeArray; if (smallArray.count > MAX_NUM_ITEMS) smallArray = [smallArray subarrayWithRange:NSMakeRange(0, MAX_NUM_ITEMS)]; 

When the array is already in the limit, this version will simply reference the existing array.

+1
Mar 29 '15 at 18:03
source share

Here's an obvious long way to do this:

 NSMutableArray* smallMutableArray; if ([largeArray count] <= x) { smallMutableArray = [largeArray copy]; } else { for (int i=0; i<x; i++) { [smallMutableArray addObject:[largeArray objectAtIndex:i]]; } } 
-5
Jul 29 '13 at 16:27
source share



All Articles