【发布时间】:2014-12-16 12:30:31
【问题描述】:
我正在使用 DetailViewController 创建一个简单的 iPad 应用程序。一切都很好,但是当我尝试使用多级 JSON 时,它不再工作了,应用程序崩溃了。
我检索并循环遍历数据:
-(void) retrieveData{
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
fruitArray = [[NSMutableArray alloc] init];
//loop through jsonarray
for(int i =0;i < jsonArray.count;i++){
NSString * cName = [[jsonArray objectAtIndex:i] valueForKey:@"cityName"];
NSString * cFruit = [[jsonArray objectAtIndex:i] valueForKey:@"fruit"];
//add object to fruitArray array
[fruitArray addObject:[[Fruits alloc]initWithCityDocumentName:cName andFruit:cFruit]];
}
//reload table view
[self.tableView reloadData];
}
使用 json:
[{
"id": "1",
"cityName": "London",
"fruit":"Apple"
}, {
"id": "2",
"cityName": "Berlin",
"fruit":"Pear"
}]
然后我设置标签(我从情节提要/NIB 中将它们连接起来):
- (void)setLabels{
cityNameLabel.text = currentCity.documentName;
fruitLabel.text = currentCity.documentFruit;
}
以上所有这些都可以正常工作。
但是,一旦我在 JSON 中为水果创建了多个值,它就不起作用了! 新 JSON:
[{
"id": "1",
"cityName": "London",
"fruit":
["Apple", "Pear", "Orange", "Lemon"]
}, {
"id": "2",
"cityName": "Berlin",
"fruit":
["Mango", "Melon", "Tomatoe", "Avocado"]
}]
在我看来,我需要以某种方式以编程方式创建标签并循环它们?基本上,我需要在详细视图控制器中查看每个 id 的多个值
我该怎么做?
我真的需要帮助 :( 谢谢。
编辑:我现在能够创建一个数组而不是字符串,但是当我从它们创建按钮时,它不会让我根据数组中的内容添加标题:
NSMutableArray * cFruit = [[jsonArray objectAtIndex:i] valueForKey:@"fruit"];
然后:
- (void)setLabels{
for(int i=0;i<=currentCity.documentFruit.count;i++){
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(setLabels)
forControlEvents:UIControlEventTouchUpInside];
//below is my error - looks like it doesn't like setting the titles from array
[button setTitle:[currentCity.documentFruit objectAtIndex:i] forState:UIControlStateNormal];
button.frame = CGRectMake(20.0, ButtonHeightPlusOffsetBetweenButtons * i , 280.0, 40.0);
//Set Tag for future identification
[button setTag:i];
[self.view addSubview:button];
}
}
【问题讨论】:
-
您将数组分配给字符串变量,然后将其用作字符串。取变量为id类型,然后检查变量的类,如果是字符串(表示水果键包含单个水果)则执行当前代码,如果是数组,则设法检索。
-
是的,你是对的。但是如何使用这个新数组来创建多个标签或文本字段?
-
您需要以编程方式创建标签或文本字段,以使其数量动态。使用循环根据您的水果数组计数创建它们
-
你能帮我怎么做吗?
-
@angular_learner 为什么要以编程方式创建文本字段?如果您只想显示值,请使用 UITableView
标签: ios iphone json ipad uisplitviewcontroller