应用程序崩溃当标题不存在时

Pra*_*rad -1 cocoa-touch objective-c nsdictionary ios instagram

我的应用程序显示Instagram图片的标题,并在每次没有标题时崩溃.我该如何防止这种情况发生?这是我正在使用的代码:

if (entry[@"caption"][@"text"]) {
    NSString *caption = entry[@"caption"][@"text"];
    UILabel *instagramCaptionLabel = (UILabel *)[cell viewWithTag:103];
    [instagramCaptionLabel setFont:[UIFont fontWithName:@"Helvetica-Light" size:12.0]];
    [instagramCaptionLabel setText:caption];
}
Run Code Online (Sandbox Code Playgroud)

这是错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull objectForKeyedSubscript:]: unrecognized selector sent to instance 0x1ed8068'

rma*_*ddy 5

根据错误消息,这意味着您确实有一个值@"caption"但它碰巧是一个NSNull对象.

你有两个选择:

1)不要NSNull在字典中放置值.

要么

2)更新你的if陈述:

if (entry[@"caption"] != [NSNull null] && entry[@"caption"][@"text"] != [NSNull null])
Run Code Online (Sandbox Code Playgroud)