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!
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.
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.
arrays can't contain nil.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With