Check if NSDictionary is empty

33,936

Solution 1

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"]);

Solution 2

if ( [mutDictValues count] == 0 ) {
    //code here
}
else {
    //code here
}

After having your dic retrieved this should do

Solution 3

try this,

if([myDict count] > 0)
    NSLog(@"Dictionary is not empty");
else
    NSLog(@"Dictionary is empty");

Solution 4

BOOL containsKeyABC = [myDict: valueForKey:@"ABC"];

int items = dict.count;

if (items > 0) {
     //not empty
}

Solution 5

Somewhere you treat a nsstring (a concrete subclass) as NSdictionary.

Share:
33,936
Steaphann
Author by

Steaphann

Updated on December 18, 2021

Comments

  • Steaphann
    Steaphann over 2 years

    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 ?

  • Steaphann
    Steaphann almost 11 years
    Is it possible to get this back as NSDictionary ?
  • Balu
    Balu almost 11 years
  • kb920
    kb920 almost 11 years
    if (![dictTemp isKindOfClass:[NSDictionary class]]) { // do something DisplayAlert(@"No data found") }