wwjdm
wwjdm

Reputation: 2596

ios: Compare NSString to "<null>" not working

I am consuming a web service that returns JSON. One of the values I get is "< null >".

When I run the follwoing code the if statment still get executed when it is not suppposed to.

Any reason why?

NSDictionary *location = [dictionary valueForKey:@"geoLocation"];       //get the product name
NSString *latitude = [location valueForKey:@"latitude"];
NSLog(@"%@", latitude);

NSString *longitude = [location valueForKey:@"longitude"];

if (![latitude isEqual: @"<null>"] && ![longitude isEqual: @"<null>"]) {
    NSLog(@"%d", i);
    CLLocationCoordinate2D coordinate;
    coordinate.longitude = [latitude doubleValue];
    coordinate.longitude = [longitude doubleValue];
    [self buildMarketsList:coordinate title:title subtitle:nil]; //build the browse list product
}

Upvotes: 12

Views: 13618

Answers (4)

Albert Tong
Albert Tong

Reputation: 411

Typically if you get null in a JSON response, you'll need to check against NSNull.

In your case, you should do something like this:

if ( [location valueForKey:@"longitude"] == [NSNull null]) {
     // is null object
} 

Upvotes: 0

lakshmen
lakshmen

Reputation: 29074

if ([latitude isEqual:[NSNull null]])
{
 //do something
 latitude = @"";
}
else
{
 //do something else
 latitude = json value
}

This is what I will do. This is because I need to store the value even if a null return.

Upvotes: 0

Harshal Chaudhari
Harshal Chaudhari

Reputation: 710

I had same Problem, But solved as below, Replace your if with following,

if (![latitude isKindOfClass:[NSNull class]] && ![longitude isKindOfClass:[NSNull class]])

Upvotes: 2

user529758
user529758

Reputation:

I am consuming a web service that returns JSON. One of the values I get is "< null >"

Aha. Two possibilities:

I. The JSON doesn't contain latitude and longitude information. In this case, the keys for them aren't present in the dictionary you're getting back, so you are in fact obtaining a nil (or NULL) pointer. As messaging nil returns zero, both conditions will fire (due to the negation applied). Try this instead:

if (latitude != nil && longitude != nil)

and never rely on the description of an object.

II. Probably the JSON contains null values, and the JSON parser you're using turns null into [NSNull null], and in turn you're trying to compare a string against that NSNull. In this case, try this:

if (![latitude isEqual:[NSNull null]] && ![longitude isEqual:[NSNull null]])

Upvotes: 31

Related Questions