【发布时间】:2014-02-27 16:38:55
【问题描述】:
我有一个 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];
}
有没有更好的方法来尝试实现我正在做的事情???
谢谢,丹。
【问题讨论】:
-
应该不需要try-catch。当您向 NSDictionary 询问不存在的条目时,它会返回
nil,您可以轻松地对其进行测试。 (事实上,你必须非常努力才能获得例外。) -
不要使用
valueForKey:,使用objectForKey:。 -
因为 valueForKey: 是一个高度复杂的方法,可以为各种不同的对象处理各种关键路径,所以它必须仔细检查路径是什么,该方法发送的对象是什么to 等等,而 objectForKey 仅用于在字典中查找内容。可能跑得快十倍。
标签: ios objective-c json uitableview try-catch