NSDictionary having null value

22,634

Solution 1

NSDictionary and other collections cannot contain nil values. When NSDictionary must store a null, a special value [NSNull null] is stored.

Compare the value at @"My Data" to [NSNull null] to determine if the corresponding value is null or not.

// Since [NSNull null] is a singleton, you can use == instead of isEqual
if ([details objectForKey:@"My Data"] == [NSNull null]) {
    // Display the alert
}

Solution 2

Usually null values in JSON get parsed to NSNull. So this condition should check for that as well as nil: if((details[@"My Data"] == nil) || (details[@"My Data"] == [NSNull null]))

Solution 3

if ([[details objectForKey:@"My Data"] isEqual:[NSNull null]] || [[details objectForKey:@"My Data"] isEqualToString:@""]) {
     UIAlertView *altTemp = [UIAlertView alloc]initWithTitle:@"Value Null" message:@"Your Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
     [altTemp show];
     [altTemp release];
}
Share:
22,634
Kalyan Urimi
Author by

Kalyan Urimi

Updated on July 02, 2020

Comments

  • Kalyan Urimi
    Kalyan Urimi almost 4 years

    I have a problem when Extracting data from a Dictionary object. Count of the Dictionary is displaying as 1, but the one value it is displaying is null. I want to display a AlertView when there is no data in the Dictionary object. I thought of displaying the AlertView when the count is '0', but it returning '1'.

    I am extracting this dictionary object from a WebService using JSON.

    {
         "My Data" = null;
    }
    

    Used this code for getting the "My Data" value into the Dictionary variable Datas.

    Datas = (NSDictionary *) [details objectForKey:@"My Data"];
    
    if ([Datas count] == 0) {
    
    //code for showing AlertView....
    
    }
    

    Please help me to display a UIAlertView when the Dictionary value having null....

  • Paras Joshi
    Paras Joshi about 11 years
    now , its right?? @PratyushaTerli i just write the answer which give some idea so just skip that point so, but thanx :)
  • Carl Veazey
    Carl Veazey about 11 years
    Why test isEqUal:NULL? If that is true it will evaluate to false and won't work for nsnull
  • Paras Joshi
    Paras Joshi about 11 years
    @CarlVeazey now its right?? and no some time from server we get value null in string also, so just convert it to string and it will work so i just define above code, and now its right... what you say??
  • Paras Joshi
    Paras Joshi about 11 years
    @CarlVeazey now its true and right and first i write NULL bcoz some time from api , and server may be return direct that type of values so.. if now right then upvote me..