How to get the first x elements of an NSArray in Cocoa?

New in Cocoa and something seems to be missing.

What is the most elegant / idiomatic way to get the first x elements of an NSArray as another NSArray ? Obviously, I can iterate over them and store them manually, but it seems that this requires a more standard method.

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

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

Thank!

+43
objective-c cocoa
Jul 29 '10 at 16:22
source share
4 answers

You can use subarrayWithRange:

 NSArray *smallArray = [largeArray subarrayWithRange:NSMakeRange(0, 10)]; 
+119
Jul 29 '10 at 16:23
source share
 firstNItems = [items subarrayWithRange:NSMakeRange(0, MIN(n, items.count))]; 
+18
Aug 28 '15 at 13:54 on
source share

The second parameter is the number of elements in the array, which should be included in the range, not the "to" index

0
Apr 27 '15 at 14:47
source share

In Swift 3, you can use this:

 let smallArray = largeArray.prefix(10) 
-one
Jan 12 '17 at 17:52
source share



All Articles