从JSON数据为NSString分配null时发生崩溃

时间:2017-11-21 09:28:25

标签: ios objective-c json nsstring

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

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

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

    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的值,那么如何避免崩溃呢?

2 个答案:

答案 0 :(得分:1)

添加检查null:

$(document).ready(function() {
    function animateText(container, el) {
        $(container).each(function() {
            var thisContainer = $(this);
            var initialColor = $(this).find(el).css("color");
            var delay = 0;
            $(thisContainer).find(el).each(function() {
                anime({
                    targets: $(this).get(0),
                    color: ["#ff0", initialColor],
                    duration: 1000,
                    loop: true,
                    delay: delay*50
                });
                delay++;
            });
        });
    }
    animateText('ul', 'li');
});

答案 1 :(得分:0)

笨拙,但是

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;