从 JSON 数据中将 null 分配给 NSString 时崩溃

Crash when assigning null to NSString from JSON data

我遇到了崩溃,我已经缩小到这行代码,但我不明白如何避免它。

NSString *variantImageUrl = variantEdge[@"node"][@"image"][@"src"];

如果 src 的值为空,应用程序会崩溃并显示以下错误消息

    2017-11-21 17:23:27.023988+0800 NWMPos[3218:2124447] -[NSNull objectForKeyedSubscript:]: unrecognized selector sent to instance 0x1b2a01650
2017-11-21 17:23:27.026199+0800 NWMPos[3218:2124447] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull objectForKeyedSubscript:]: unrecognized selector sent to instance 0x1b2a01650'

只要 src 的值是正确的字符串就可以正常工作

但是我无法在赋值之前检查 null 的值,所以如何避免崩溃?

添加空值检查:

if(![variantEdge[@"node"][@"image"][@"src"] isEqual:[NSNull null]])
{
    NSString *variantImageUrl = variantEdge[@"node"][@"image"][@"src"];
}

非常笨拙,但是

NSDictionary *dict = variantEdge;

for (NSString *key in @[@"node", @"image"]) {
   dict = dict[key];
   if (![dict isKindOfClass:NSDictionary.class]) {
      dict = nil;
      break;
   }
}

NSString *url = dict ? dict["src"] : nil;