我想在 iphone 中获取 NSMutableDictionary 计数。我想知道 NSMutableDictionry 中有多少项。我尝试了这些代码来找出解决方案,但对我帮助不大。
NSLog(@"Count : %d", [mutableDictionary count]);
它总是返回'0'。如何在 iPhone 中获取 NSMutableDictionary 的计数?提前致谢。
最佳答案
你可以找出有多少个键-对象(键-值)对,像这样:
NSArray * allKeys = [mutableDictionary allKeys];
NSLog(@"Count : %d", [allKeys count]);
编辑
查看字典文档后,NSDictionary
的count
方法(或属性)应该也能正常工作。我想你可能一直收到 0 计数,因为字典是空的或零。我提供我的解决方案是因为我更关心枚举键而不是直接计算条目。
请考虑您已在其他地方解决该问题。
• 通过实际填充字典
或者
• 通过修复 mutableDictionary 不知何故为 nil 的错误
我运行这个测试代码并得到注释输出
NSMutableDictionary * countDict = [NSMutableDictionary dictionaryWithObject:@"test" forKey:@"test"];
[countDict setObject:@"foo" forKey:@"bar"];
NSLog(@"test count %d", countDict.count); //test count 2
countDict = nil;
NSLog(@"test count %d", countDict.count); //test count 0
关于iphone - 如何在 iphone 中获取 NSMutableDictionary 计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8815375/