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.
获得NSArray的第一个x元素作为另一个NSArray的最优雅/惯用方法是什么?显然,我可以遍历它们并手工存储它们,但似乎必须有更标准的方法来实现这一点。
I was expecting there to be an -arrayWithObjectsInRange:
or something similar, but don't see anything...
我原以为会有一个-arrayWithObjectsInRange:或者类似的东西,但什么都没看到……
NSArray* largeArray...// Contains 50 items...
NSArray* smallArray = // fill in the blank
// smallArray contains first 10 items from largeArray
Thanks!
谢谢!
4 个解决方案
#1
122
You can use subarrayWithRange:
.
您可以使用subarrayWithRange:。
NSArray *smallArray = [largeArray subarrayWithRange:NSMakeRange(0, 10)];
#2
19
firstNItems = [items subarrayWithRange:NSMakeRange(0, MIN(n, items.count))];
#3
0
2nd parameter is number of array items to include in the range, not the 'to' index
第二个参数是要包含在范围中的数组项的数量,而不是“to”索引
#4
-1
In Swift 3 you can use this:
在Swift 3中,您可以使用以下内容:
let smallArray = largeArray.prefix(10)
#1
122
You can use subarrayWithRange:
.
您可以使用subarrayWithRange:。
NSArray *smallArray = [largeArray subarrayWithRange:NSMakeRange(0, 10)];
#2
19
firstNItems = [items subarrayWithRange:NSMakeRange(0, MIN(n, items.count))];
#3
0
2nd parameter is number of array items to include in the range, not the 'to' index
第二个参数是要包含在范围中的数组项的数量,而不是“to”索引
#4
-1
In Swift 3 you can use this:
在Swift 3中,您可以使用以下内容:
let smallArray = largeArray.prefix(10)