ios:将NSString与"<null>"进行比较不起作用

wwj*_*jdm 12 null json nsstring ios

我正在使用返回JSON的Web服务.我得到的价值之一是"< null >".

当我运行以下代码时,如果不支持,则if语句仍会执行.

有什么理由吗?

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
}
Run Code Online (Sandbox Code Playgroud)

小智 31

我正在使用返回JSON的Web服务.我得到的一个值是"<null>"

啊哈.两种可能性:

I. JSON不包含纬度和经度信息.在这种情况下,它们的键不存在于您要返回的字典中,因此您实际上正在获取nil(或NULL)指针.当消息传递nil返回零时,两个条件都将触发(由于应用了否定).试试这个:

if (latitude != nil && longitude != nil)
Run Code Online (Sandbox Code Playgroud)

而且从不依赖于对象的描述.

II.可能JSON包含null值,并且您正在使用的JSON解析器变成null[NSNull null],反过来,您正在尝试将字符串与该字符串进行比较NSNull.在这种情况下,试试这个:

if (![latitude isEqual:[NSNull null]] && ![longitude isEqual:[NSNull null]])
Run Code Online (Sandbox Code Playgroud)