Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if NSDictionary is empty

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 ?

like image 491
Steaphann Avatar asked Jul 19 '13 11:07

Steaphann


People also ask

How do I check if a dictionary is empty in Objective C?

To check if a dictionary is empty, you can either check if the size of the dictionary is zero or use the isEmpty function. The type of keys array is same as that of keyType , and the type of values array is same as that of valueType .

What is NSDictionary in Swift?

In Swift, the NSDictionary class conforms to the DictionaryLiteralConvertible protocol, which allows it to be initialized with dictionary literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).


2 Answers

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"]);
like image 175
Balu Avatar answered Oct 06 '22 00:10

Balu


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

After having your dic retrieved this should do

like image 29
rashii Avatar answered Oct 06 '22 01:10

rashii