Check if NSDictionary is Null?

后端 未结 5 1723
伪装坚强ぢ
伪装坚强ぢ 2021-02-13 07:14

I\'ve tried multiple ways. I know the dictionary is NULL, as the console also prints out when I break there. Yet when I put it in an if( ) it doesn\'t trigger.



        
相关标签:
5条回答
  • 2021-02-13 07:22
    if([NSNull null] != [serverResponseObject objectForKey:@"Your_Key"])
    {
    //Success
    }
    
    0 讨论(0)
  • 2021-02-13 07:23

    It looks like you have a dangling or wild pointer.

    You can consider Objective-C objects as pointers to structs.

    You can then of course compare them with NULL, or with other pointers.

    So:

    ( myDict == NULL )
    

    and

    ( myDict == [ NSNull null ] )
    

    are both valid.

    The first one will check if the pointer is NULL. NULL is usually defined as a void * with a value of 0.
    Note that, for Objective-C objects, we usually use nil. nil is also defined as a void * with a value of 0, so it equals NULL. It's just here to denote a NULL pointer to an object, rather than a standard pointer.

    The second one compares the address of myDict with the singleton instance of the NSNull class. So you are here comparing two pointers values.

    So to quickly resume:

    NULL == nil == Nil == 0
    

    And as [ NSNull null ] is a valid instance:

    NULL != [ NSNull null ]
    

    Now about this:

    ( [ myDict count ] == 0 )
    

    It may crash if you have a wild pointer:

    NSDictionary * myDict;
    
    [ myDict count ];
    

    Unless using ARC, it will surely crash, because the myDict variable has not been initialised, and may actually point to anything.

    It may also crash if you have a dangling pointer:

    NSDictionary * myDict;
    
    myDict = [ [ NSDictionary alloc ] init ];
    
    [ myDict release ];
    [ myDict count ];
    

    Then you'll try to send a message to a deallocated object.
    Sending a message to nil/NULL is always valid in Objective-C.

    So it depends if you want to check if a dictionary is nil, or if it doesn't have values (as a valid dictionary instance may be empty).

    In the first case, compare with nil. Otherwise, checks if count is 0, and ensure you're instance is still valid. Maybe you just forgot a retain somewhere.

    0 讨论(0)
  • 2021-02-13 07:24
    if (TheDict == (NSDictionary*) [NSNull null]){
    
    //TheDict is null
        }
    else{
    //TheDict is not null
    
    }
    
    0 讨论(0)
  • 2021-02-13 07:24

    To check if a dictionary has nil or NULL data, you can check for the [dictionary count] which will return 0 in all cases

    0 讨论(0)
  • 2021-02-13 07:47

    All above doesn't work for me but this

    if([mydict isKindOfClass:[NSNull class]])
    {
       NSLog("Dic is Null")
    }
    else
    {
       NSLog("Dic is Not Null")  
    }
    

    Worked for me

    0 讨论(0)
提交回复
热议问题