检查NSDictionary是否为空

我想检查NSDictionary是否为空。 我是这样做的。

  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]; } 

但它在这一行崩溃了arrCities = [mutDictValues objectForKey:@"cities"]; 出现以下错误:

 -[__NSCFConstantString objectForKey:]: 

有人可以帮我弄这个吗 ?

从NSUserDefaults检索字典值时,该字典自动转换为字符串,这是导致崩溃和检查字典使用的原因

 [dictionary count]; 

编辑: – 使用dictionaryForKey:方法

 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 } 

检索完你的dic之后应该这样做

尝试这个,

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

在某处你将nsstring(一个具体的子类)视为NSdictionary。

我有一个不同的问题,但它是相关的,所以我想在这里分享。

我正在获取Web服务并在NSDictionary中存储数据并再次获取Null的objectForKey。 所以我发现的解决方案就是如此

 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 } 

使用NSNull背后的原因是当我调试应用程序时它返回(NSNull *)所以我终于想通了这种方式。

由于大多数答案都正确地指出您将未识别的选择器objectForKey:传递给NSString实例而不是NSDictionary ,因此观察exception

 -[__NSCFConstantString objectForKey:]: 

检查NSUserDefaults以查看cities是否返回字典或其他内容。 你可以通过两种方式做到这一点

I. NSLog NSUserDefaults所有数据

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

II。 检查从Application文件夹中存储NSUserDefaults的plist文件。 查看此答案以获取更多详细信息

希望有所帮助。

 BOOL containsKeyABC = [myDict: valueForKey:@"ABC"]; int items = dict.count; if (items > 0) { //not empty } 

试试这段代码

 NSMutableDictionary *dict = ... BOOL isEmpty = ([dict count] == 0); 

您可以使用以下代码

 if(dict == nil) { // blank }else{ // there is dictionary }