作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我在 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/
我是一名优秀的程序员,十分优秀!