Harry Wood
Harry Wood

Reputation: 2351

How do I get the first X elements of an unknown size NSArray?

In objectiveC I have an NSArray, let's call it NSArray* largeArray, and I want to get a new NSArray* smallArray with just the first x objects

...OR in the event that largeArray is already size <= x I just want a copy of the largeArray. So truncating any objects after index x.

This approach:

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

Was the answer to this very similar question. But it fails with an error if largeArray is already small.

Upvotes: 11

Views: 3251

Answers (3)

John Stephen
John Stephen

Reputation: 7734

Fogmeister's answer is perfectly good, but, in situations where the array is often already small enough, that answer will be mildly inefficient since 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 within the limit this version will just make a reference to the existing array.

Upvotes: 1

Fogmeister
Fogmeister

Reputation: 77641

You could do this...

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

That will take the first x elements or the full array if it's smaller than x.

If largeArray.count is 100.

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

Yep, that works :D

Upvotes: 29

Harry Wood
Harry Wood

Reputation: 2351

Here's the obvious long-hand way of doing it:

NSMutableArray* smallMutableArray;
if ([largeArray count] <= x) {
    smallMutableArray = [largeArray copy];
} else {
    for (int i=0; i<x; i++) {
       [smallMutableArray addObject:[largeArray objectAtIndex:i]];
    }
}

Upvotes: -5

Related Questions