Check if NSDictionary is empty

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 10:40:57

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"]);
rashii
if ( [mutDictValues count] == 0 ) {
    //code here
}
else {
    //code here
}

After having your dic retrieved this should do

try this,

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

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

I had a bit different issue but it is related so i would like to share it here.

I was fetching the webservices & storing data in NSDictionary & again Fetching objectForKey which was Null. So the solution i found is as under

NSMutableDictionary *result = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

    // NSLog(@"%@" , result);

    NSMutableDictionary *sup = [result objectForKey:@"keysupplied"];
    NSNull *n=[NSNull null];
    if ( sup ! = n ){
      //Your code if its not null
    }

The reason behind using NSNull was it was returning (NSNull *) when i debugged the application So i finally figured out this way.

Amar

As most of the answers have correctly pointed out that you are passing un-recognized selector objectForKey: to a NSString instance instead of NSDictionary, hence observing exception

-[__NSCFConstantString objectForKey:]:

Check NSUserDefaults to see whether cities returns a dictionary or something else. You can do this by two ways

I. NSLog all data in NSUserDefaults

NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

II. Check the plist file which store the NSUserDefaults from the Application folder. Check this answer for more details.

Hope that helps.

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

int items = dict.count;

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

try this code

NSMutableDictionary *dict = ...

BOOL isEmpty = ([dict count] == 0);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!