I am experiencing a crash that I have narrowed down to this line of code but I dont understand how I can avoid it.
我遇到了崩溃,我已经缩小到这行代码,但我不明白我怎么能避免它。
NSString *variantImageUrl = variantEdge[@"node"][@"image"][@"src"];
If the value of src is null the app crashes with the following error message
如果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'
As long as the value of src is a proper string it works fine
只要src的值是一个合适的字符串,它就可以正常工作
But I cannot check the value for null before I assign it so how can avoid the crash?
但是在分配之前我无法检查null的值,那么如何避免崩溃呢?
2 个解决方案
#1
1
Add check for null:
添加检查null:
if(![variantEdge[@"node"][@"image"][@"src"] isEqual:[NSNull null]])
{
NSString *variantImageUrl = variantEdge[@"node"][@"image"][@"src"];
}
#2
0
Clumsy as hell, but
笨拙地说,但是
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;
#1
1
Add check for null:
添加检查null:
if(![variantEdge[@"node"][@"image"][@"src"] isEqual:[NSNull null]])
{
NSString *variantImageUrl = variantEdge[@"node"][@"image"][@"src"];
}
#2
0
Clumsy as hell, but
笨拙地说,但是
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;