我正在使用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];
}
}
答案 0 :(得分:1)
fruitArray数组是方法中的局部变量。它从不存储在任何地方。无论你投入什么,它都不会有任何影响。
顺便说一句。
使用for循环(如jsonArray中的NSDictionary * dict),避免每次都进行慢速索引操作。
假设关键水果包含一个字符串,当它包含一个数组时。这迟早会使你的程序崩溃。
不要使用valueForKey,请使用objectForKey。最终,您将通过valueForKey获得非常令人惊讶的结果。
答案 1 :(得分:1)
更新JSON之后,您不会收到NSString对象,而是收到NSArray:
NSString * cFruit = [[jsonArray objectAtIndex:i] valueForKey:@"fruit"];
所以你需要做这样的事情:
NSArray *fruitsArray = [[jsonArray objectAtIndex:i] valueForKey:@"fruit"];
NSString *cFruit = [fruitsArray componentsJoinedByString:@","];
答案 2 :(得分:1)
我在这里为您提供完整的代码
#import "ViewController.h"
#import "FruitsBO.h"
@interface ViewController ()
@property (strong, nonatomic) IBOutlet UITableView *tblFruit;
@property (nonatomic, strong) NSMutableArray *arrFruitData;
@end
@implementation ViewController
@synthesize arrFruitData;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrFruitData = [[NSMutableArray alloc] init];
[self loadLocalJson];
}
-(void)loadLocalJson
{
NSString *pathStringToLocalFile = [[NSBundle mainBundle] pathForResource:@"Fruit" ofType:@"json"];
NSError *deserializingError;
NSURL *localFileURL = [NSURL fileURLWithPath:pathStringToLocalFile];
NSData *contentOfLocalFile = [NSData dataWithContentsOfURL:localFileURL];
NSArray *objects = [NSJSONSerialization JSONObjectWithData:contentOfLocalFile
options:NSJSONReadingAllowFragments
error:&deserializingError];
[self parseFruit:objects];
}
-(void)parseFruit:(NSArray *)arrFruits
{
for (NSDictionary *dictTemp in arrFruits) {
FruitsBO *fruit = [[FruitsBO alloc] init];
fruit.fruitID = [dictTemp objectForKey:@"id"];
fruit.cityName = [dictTemp objectForKey:@"cityName"];
fruit.arrFruit = [dictTemp objectForKey:@"fruit"];
[arrFruitData addObject:fruit];
fruit = nil;
}
[self.tblFruit reloadData];
}
#pragma mark - TableView Delegate -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.arrFruitData count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
FruitsBO *obj = [self.arrFruitData objectAtIndex:section];
return [obj.arrFruit count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
FruitsBO *obj = [self.arrFruitData objectAtIndex:section];
return obj.cityName;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"fruitIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
FruitsBO *objTemp = [self.arrFruitData objectAtIndex:indexPath.section];
cell.textLabel.text = [objTemp.arrFruit objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
这是我的Json
[{
"id": "1",
"cityName": "London",
"fruit":
["Apple", "Pear", "Orange", "Lemon"]
}, {
"id": "2",
"cityName": "Berlin",
"fruit":
["Mango", "Melon", "Tomatoe", "Avocado"]
},{
"id": "2",
"cityName": "Austin",
"fruit":
["Mango"]
}]
这是我的输出