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

后端 未结 3 857
清酒与你
清酒与你 2021-02-20 01:59

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

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-20 02:59

    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.

提交回复
热议问题