Check if NSDictionary is empty

Steaphann picture Steaphann · Jul 19, 2013 · Viewed 31.8k times · Source

I want to check if an NSDictionary is empty. I am doing it like this.

  mutDictValues = [[[NSUserDefaults standardUserDefaults] objectForKey:@"dicValues"]mutableCopy];
    NSLog(@"dictValues are %@",mutDictValues);
    if(mutDictValues == NULL){
        arrCities = [[NSMutableArray alloc]init];
        NSLog(@"no cities seleceted");
    }else{
          arrCities = [[NSMutableArray alloc]init];
          arrCities = [mutDictValues objectForKey:@"cities"];
          [self placeCities];
    }

But it alwasy crashes on this line arrCities = [mutDictValues objectForKey:@"cities"]; with the following error:

-[__NSCFConstantString objectForKey:]:

Can someone help me with this ?

Answer

Balu picture Balu · Jul 19, 2013

While retrieving the dictionary values from NSUserDefaults that dictionary automatically converted into string that is the reason for getting crashed and for checking dictionary use

[dictionary count];

EDIT:- use dictionaryForKey: method

NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"hi",@"one",nil];
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"dic"];
NSDictionary *dictn = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"dic"];
NSLog(@"%@",[dictn objectForKey:@"one"]);