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

后端 未结 3 858
清酒与你
清酒与你 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

    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

提交回复
热议问题