Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get first x elements of an NSArray in Cocoa?

New to Cocoa, and seem to be missing something.

What is the most elegant/idiomatic way to obtain the first x elements of an NSArray as another NSArray? Obviously I can iterate through them and store them manually, but it seems like there has to be a more standard method of doing this.

I was expecting there to be an -arrayWithObjectsInRange: or something similar, but don't see anything...

NSArray* largeArray...// Contains 50 items...  NSArray* smallArray = // fill in the blank       // smallArray contains first 10 items from largeArray 

Thanks!

like image 729
CocoaNewb Avatar asked Jul 29 '10 16:07

CocoaNewb


People also ask

What is the key 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.

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.

Can NSArray contain nil?

arrays can't contain nil.

What is NSArray Objective-C?

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


1 Answers

You can use subarrayWithRange:.

NSArray *smallArray = [largeArray subarrayWithRange:NSMakeRange(0, MIN(10, largeArray.count))];//MIN() used because array must be larger than or equal to range size, else exception will be thrown 
like image 116
mipadi Avatar answered Oct 21 '22 07:10

mipadi