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 ?
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 .
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).
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"]);
if ( [mutDictValues count] == 0 ) {
//code here
}
else {
//code here
}
After having your dic retrieved this should do
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With