ios NSD字典计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11741360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSDictionary Count
提问by Lucas Veiga
how can I count how many itens do I have inside of "bills"?
我如何计算“账单”中有多少个项目?
bills = (
{
id = 1;
name = "Cursus Nibh Venenatis";
value = "875.24";
},
{
id = 2;
name = "Elit Fusce";
value = "254.02";
}
);
I'm counting this way:
我是这样数的:
NSUInteger keyCount = [resultsDictionary count];
NSLog(@"%i", keyCount);
Thanks!
谢谢!
采纳答案by Henri Normak
A naive solution would assume the OP wants to count bills
, which happens to be an array, so the solution would be
一个天真的解决方案会假设 OP 想要 count bills
,这恰好是一个数组,所以解决方案是
NSLog(@"Count: %i", [[resultsDictionary objectForKey: @"bills"] count]);
However, if you have a dictionary with more than one object you want to count, then enumerating them all is the only way to go.
但是,如果您的字典包含多个要计算的对象,则将它们全部枚举是唯一的方法。
回答by ilhnctn
NSUInteger keyCount = [resultsDictionary count];
NSLog(@"%i", keyCount);
is true but also you can use [resultsDictionary allKeys];
which will return an array of keys and you can directly get its count. For more, please visit docs:v
是真的,但你也可以使用[resultsDictionary allKeys];
它返回一个键数组,你可以直接得到它的计数。有关更多信息,请访问文档:v
回答by Prasad G
NSMutableArray *billsArray =[[NSMutableArray alloc] init];
billsArray = [resultsDictionary valueForKey:@"bills"];//returns array
NSUInteger keyCount = [billsArray count];
NSLog(@"%i", keyCount);
I think it will be helpful to you.
我想它会对你有所帮助。
回答by David H
NSUInteger count = [bills count];
// top level items in the dictionary
NSUInteger count = [bills count];
// 字典中的顶级项目
If you want to get ALL items, then you need to use block enumeration and recursively ask every dictionary what the count is and then sum. You have to write code - there is no system provided method to do this. Look at the block enumerations (ie enumerate....) in the class reference.
如果您想获取所有项目,那么您需要使用块枚举并递归地询问每个字典的计数是多少,然后求和。您必须编写代码 - 没有系统提供的方法来执行此操作。查看类参考中的块枚举(即枚举....)。
you can also ask each item what it is - and if "isKindOf:" a NSDictionary or NSArray, get the count, otherwise treat it as 1.
您还可以询问每个项目它是什么 - 如果“isKindOf:”是 NSDictionary 或 NSArray,则获取计数,否则将其视为 1。