Check if NSDictionary is empty

后端 未结 8 951
名媛妹妹
名媛妹妹 2021-02-13 02:40

I want to check if an NSDictionary is empty. I am doing it like this.

  mutDictValues = [[[NSUserDefaults standardUserDefaults] objectForKey:@\"dicV         


        
相关标签:
8条回答
  • 2021-02-13 03:14

    try this,

    if([myDict count] > 0)
        NSLog(@"Dictionary is not empty");
    else
        NSLog(@"Dictionary is empty");
    
    0 讨论(0)
  • 2021-02-13 03:15

    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"]);
    
    0 讨论(0)
  • 2021-02-13 03:15

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

    0 讨论(0)
  • 2021-02-13 03:19

    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.

    0 讨论(0)
  • 2021-02-13 03:21

    try this code

    NSMutableDictionary *dict = ...
    
    BOOL isEmpty = ([dict count] == 0);
    
    0 讨论(0)
  • 2021-02-13 03:22
    BOOL containsKeyABC = [myDict: valueForKey:@"ABC"];
    
    int items = dict.count;
    
    if (items > 0) {
         //not empty
    }
    
    0 讨论(0)
提交回复
热议问题