如何获取未知大小的 NSArray 的第一个 X 元素? [英] How do I get the first X elements of an unknown size NSArray?

查看:39
本文介绍了如何获取未知大小的 NSArray 的第一个 X 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在objectiveC中,我有一个NSArray,我们称之为NSArray* largeArray,我想得到一个新的NSArray* smallArray,其中只有前x个对象

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

...或者如果 largeArray 已经是 size <= x 我只想要一个 largeArray 的副本.所以在索引 x 之后截断任何对象.

...OR in the event that largeArray is already size <= x I just want a copy of the largeArray. So truncating any objects after index x.

这种方法:

NSArray *smallArray = [largeArray subarrayWithRange:NSMakeRange(0, x)];

这是这个的答案非常相似的问题.但如果 largeArray 已经很小,它会失败并出现错误.

Was the answer to this very similar question. But it fails with an error if largeArray is already small.

推荐答案

你可以这样做...

NSArray *smallArray = [largeArray subarrayWithRange:NSMakeRange(0, MIN(x, largeArray.count))];

如果它小于 x,这将采用前 x 个元素或整个数组.

That will take the first x elements or the full array if it's smaller than x.

如果 largeArray.count 是 100.

If largeArray.count is 100.

如果 x = 110,那么它将取前 100 个结果.如果 x = 90,则取前 90 个结果.

If x = 110 then it will take the first 100 results. If x = 90 then it will take the first 90 results.

是的,行得通:D

这篇关于如何获取未知大小的 NSArray 的第一个 X 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆