检查JSON值是否存在 - iOS

Sup*_*off 0 json objective-c try-catch uitableview ios

我有一个iOS应用程序,它下载并解析Twitter JSON提要,然后在UITableView中显示该提要.一切正常,但我有一个问题:

当用户点击UITableView单元格时,应用程序将查看数组"tweets_links"并查看该特定推文是否有附加的URL,如果有,则会显示Web视图.

因为并非所有的推文都有网站URL,所以我添加了一个简单的try catch语句(比如在C++中),它可以告诉我在尝试访问数组的那一部分时是否存在异常.

我的问题是:这是好的还是坏的做法?

这是我的代码:

int storyIndex = indexPath.row;
int url_test = 1;
NSString *url;

@try {
    url = [[tweets_links[storyIndex] valueForKey:@"url"] objectAtIndex:0];
}

@catch (NSException *problem) {
    // There is NO URL to access for this Tweet. Therefore we get the out of bounds error.
    // We will NOT take the user to the web browser page.
    // Uncomment the line below if you wish to see the out of bounds exception.
    // NSLog(@"%@", problem);
    url_test = 0;
}

if (url_test == 1) {
    WebBrowser *screen = [[WebBrowser alloc] initWithNibName:nil bundle:nil];
    self.seconddata = screen;
    seconddata.web_url = url;
    screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:screen animated:YES completion:nil];
}

else if (url_test == 0) {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Info" message:@"There is no URL attatched to this Tweet." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [alertView show];

    [tweetTableView deselectRowAtIndexPath:indexPath animated:YES];
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来尝试实现我正在做的事情?

谢谢,丹.

Abi*_*ern 5

使用try和catch是不鼓励Objective-C有其他方法检查和处理错误

// firstObject will return the first object in the array or nil if the array is empty.
url = [[tweets_links[storyIndex][@"url"]] firstObject];

if (!url) {
    // handle the case for no url
} else {
    // do something with url
}
Run Code Online (Sandbox Code Playgroud)

由于nil在Objective-C中发送消息是安全的,并且返回nil链接调用是安全的.例如,如果字典没有该键的对象,那么它将返回nil并发firstObject送给nil返回nil.