【发布时间】:2018-06-09 18:03:07
【问题描述】:
我正在尝试使用 iOS 学习 json。
我正在尝试使用UITableView 实现json 数据。在我的表格视图行中,标题和副标题正在显示这些值。我可以在标题中加载数据,但是当尝试在字幕中加载时,应用程序崩溃了,因为在 subtitle result 中给出了 json 的该字段和许多键对值。所以无法在tableview的副标题中显示。
我的问题是如何加载字幕,以及当单击它时是否可以使用许多键对值中的键,它会被重定向到其他 tableview 以显示该数据。
我的代码:
- (void)viewDidLoad {
[super viewDidLoad];
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://query.yahooapis.com/v1/public/yql?q=select+*+from+weather.forecast+where+woeid%3D1100661&format=json"]];
NSError *error=nil;
id response=[NSJSONSerialization JSONObjectWithData:data options:
NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];
if (error) {
NSLog(@"%@",[error localizedDescription]);
} else {
_query = [response objectForKey:@"query"];
NSLog(@"%@",_query);
_keyArray = [_query allKeys];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_keyArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] ;
}
NSString *key = [_keyArray objectAtIndex:indexPath.row];
//NSString *dictionary = [_query objectForKey:key];
NSString *dictionary = [_query objectForKey:key];
cell.textLabel.text = key;
cell.detailTextLabel.text = dictionary;
return cell;
}
谢谢。
【问题讨论】:
-
取决于 .. 你想在 cell.detailTextLabel 中显示什么?
-
我非常努力地理解你真正想要在这里得到的输出,但我不能。请添加一张图片,其中提到了您真正想要的结果。
-
如果subtitle的值是新的字典,是扩展tableview还是push到新的tableview显示子键值对。
-
@ArunKumar 我会在键值中显示 cell.detailTextLabel。但结果是许多密钥对可用,因此应用程序将崩溃。
-
您可以在设置为detailTextlabel之前检查字典的类型。 cell.detailTextLabel.text = [字典 isKindOfClass:[NSString 类]] ?字典:“变量不是字符串”
标签: ios objective-c json uitableview nsdictionary