How to get NSMutableDictionary count in iphone?
Asked Answered
C

4

13

I want to get NSMutableDictionary count in iphone. I want to know how many items are in NSMutableDictionry. I tried these code to find out the solution but, not helped me lot.

NSLog(@"Count : %d", [mutableDictionary count]);

It is always returns '0'. How to get the count of NSMutableDictionary in iPhone? Thanks in advance.

Currajong answered 11/1, 2012 at 7:1 Comment(0)
H
32

You can find out how many key-object (key-value) pairs there are like so:

NSArray * allKeys = [mutableDictionary allKeys];
NSLog(@"Count : %d", [allKeys count]);

EDIT

Upon looking through the dictionary documentation, NSDictionary's count method (or property) should work as well. I think you may have been receiving 0 count because the dictionary was empty or nil. I offered my solution because I tend to care more about enumerating the keys than counting the entries directly.

Please consider the fact that you fixed the issue somewhere else.
• By actually populating the dictionary
or
• By fixing a bug where mutableDictionary was somehow nil

I run this test code and get the commented output

  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
Hippy answered 11/1, 2012 at 7:3 Comment(0)
C
11

[[dictionary allKeys] count]; will do the trick.

Cancan answered 11/1, 2012 at 7:5 Comment(0)
T
2
     NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"Rakesh",@"Name",@"[email protected]",@"Email",nil];
     NSLog(@"Count : %d", [dict count])

Try this

Trinidadtrinitarian answered 11/1, 2012 at 7:8 Comment(1)
@RakeshBhatt +1 from me. I edited my answer after some research into the count method. I believe the OP had some other issue that has since been resolved.Hippy
C
0

if you looking to count NSMutableDictionary values for any Array item you can use.

NSLog(@"myDictionaryCount %lu", (unsigned long)[myDictionary[@"items"] count]);
Cytogenesis answered 21/1, 2014 at 2:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.