我有一个iOS应用程序下载并解析Twitter JSON供稿,然后在UITableView中呈现该供稿。这一切都很好,但我有一个问题:检查JSON值是否存在 - iOS
当用户点击一个UITableView单元格时,应用程序将查看数组“tweets_links”,看看该特定的tweet是否有附加的URL,如果它然后在网络视图会出现。
因为不是所有的微博有网站网址,我添加了一个简单的尝试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];
}
有没有的努力实现我在做什么更好的办法???
谢谢,丹。
应该没有必要尝试赶上。当你向NSDictionary询问一个不存在的条目时,它返回'nil',你可以很容易地测试它。 (事实上,你必须努力获得一个例外。) –
并且不要使用'valueForKey:',使用'objectForKey:'。 – rmaddy
因为valueForKey:是一个非常复杂的方法,它可以处理各种不同对象的各种关键路径,因此必须仔细检查路径是什么,方法发送到哪种对象等等。 objectForKey仅用于查找字典中的内容。可能运行速度快十倍。 – gnasher729