how to check for null object returned in xcode

12,705

Solution 1

A JSON "null" value is converted to [NSNull null], which you can check for with

if (text == [NSNull null]) ...

because it is a singleton.

Alternatively, you can check if the object contains the expected type, i.e. a string:

NSString *text = [obj objectForKey:@"BillingStreet"];
if ([text isKindOfClass:[NSString class]]) {
    self.labelCustomerAddress.text = text;
} else {
    self.labelCustomerAddress.text = @"no street";
}

This is more robust in the case that a server sends bad data, e.g. a number or an array instead of a string.

Solution 2

text == nil ? @"0" : text

or

text ? text : @"0"

But if you get it from JSON then you may get instance of NSNull class. In this case you should check

text && ![text isKindOfClass:[NSNull class]] ? text : @"0"

Share:
12,705
Bartley
Author by

Bartley

Certified Force.com Developer, Salesforce Administrator and Advanced Administrator. A passionate "Salesfornian" hungry to explore every nook and cranny of functionality that can be delivered from the platform. Always having one eye on building connected apps for the iOS platform along with this eye ;-) on enterprise-class solutions for global organisations. My aim is to bring rapid, organised and painless transformation to businesses wanting to become the new hyper-connected and hyper-responsive customer-oriented organisations of the future.

Updated on August 07, 2022

Comments

  • Bartley
    Bartley almost 2 years

    I have a NULL object returned from a JSON query string and I don't know how to check for it in an If statement. My syntax is below but I still don't seem to be able to trap for the NULL class (i.e., if nothing is returned then no text variable can be set therefore it MUST be a NULL class?), anyway, I need to check that the @"BillingStreet" has something in it and if not to avoid processing it (else the app crashes as it tries to set nothing to the text value of one of the fields in the VC):

    - (void) tableView: (UITableView *)itemTableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath{
        NSDictionary *obj = [self.dataCustomerDetailRows objectAtIndex:indexPath.row];
        NSString *text = [obj objectForKey:@"BillingStreet"] == nil ? @"0" : [obj objectForKey:@"BillingStreet"];
        NSLog(@"%@",text);
        if (text.class == NULL){
        } else {
            NSLog(@"no street");
            self.labelCustomerAddress.text = [obj objectForKey:@"BillingStreet"];
        }
    }