gpt4 book ai didi

ios - Objective-C : Is there a built-in way to count the total number of items in a 2d/nested NSArray?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:24 26 4
gpt4 key购买 nike

我在 Objective C 中有一个二维的 NSArray。

我想知道数组中项目的总数。在不使用嵌套 for 循环的情况下,是否有更快的方法来获取项目的总数?

谢谢!

最佳答案

是的,你可以做这个键值编码和the collection operators :

NSArray *nested = @[@[@1, @2, @3],    @[@4, @5, @6],    @[@7, @8, @9],
@[@10, @11, @12], @[@13, @14, @15], @[@16, @17, @18],
@[@19, @20, @21], @[@22, @23, @24]];
NSLog(@"%@", [nested valueForKeyPath:@"@sum.@count"]); // logs 24 (as an NSNumber)

一些评论:

关键路径 @sum.@count 首先创建一个计数数组(所以 @[@3, @3, @3, @3, @3, @ 3, @3, @3]) 然后对该数组求和(得到 @24)。

但是,这只是在编写更少代码的意义上“更快”。从根本上说,它仍然在做你自己会做的事情。而且它的效率可能较低,因为它处理的是 NSNumbers 的添加,这不如添加基元(您可能会使用)那样高效。

真的有那么难做吗:

NSUInteger total = 0;
for (NSArray *array in nested) {
total += array.count;
}

关于ios - Objective-C : Is there a built-in way to count the total number of items in a 2d/nested NSArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21656119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com