Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

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.

like image 891
Harry Wood Avatar asked Jul 29 '13 16:07

Harry Wood


People also ask

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.

What is NSArray?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

Is NSArray ordered?

In Objective-C, arrays take the form of the NSArray class. An NSArray represents an ordered collection of objects. This distinction of being an ordered collection is what makes NSArray the go-to class that it is.


1 Answers

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

like image 51
Fogmeister Avatar answered Sep 21 '22 14:09

Fogmeister