Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get NSMutableDictionary count in iphone?

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.

like image 389
Gopinath Avatar asked Jan 11 '12 07:01

Gopinath


People also ask

How do you convert NSDictionary to NSMutableDictionary?

Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.

How do you add value in NSMutableDictionary?

[myDictionary setObject:nextValue forKey:myWord]; You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil).

What is NSMutableDictionary?

An object representing a dynamic collection of key-value pairs, for use instead of a Dictionary variable in cases that require reference semantics.

Is NSDictionary thread safe?

In general, the collection classes (for example, NSMutableArray , NSMutableDictionary ) are not thread-safe when mutations are concerned. That is, if one or more threads are changing the same array, problems can occur.


1 Answers

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
like image 115
Jesse Black Avatar answered Oct 04 '22 20:10

Jesse Black