iOS - DetailViewController 不显示来自 JSON 的多个条目/值

标签 ios iphone json ipad uisplitviewcontroller

我正在使用 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"
}]

然后我设置标签(我从 Storyboard /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"]
}]

在我看来,我需要以某种方式以编程方式创建标签并循环它们?基本上,我需要在详细 View Controller 中查看每个 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];

    }
    }

最佳答案

在这里,我为您提供完整的代码,这样做

#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"]
  }]

这是我的输出

Output

关于iOS - DetailViewController 不显示来自 JSON 的多个条目/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27504728/

相关文章:

ios - 如何获取 iPhone 的 UDID?

javascript - 格式错误的 JSON 响应

python - 在python中将字符串转换为字典

iphone - 我如何在 iOS 中实现一个字符串过滤算法来反射(reflect) 'Messages' 中的联系人自动完成?

ios - 需要在 ios 应用程序而不是 safari 中打开 Facebook 页面

iphone - NSSortDescriptor,获取按日期排序的最新 5 条记录

ios - 有什么方法可以在不使用 IDFA 的情况下为设备生成唯一 ID?

java - Spring MVC REST Json 转换异常

ios - 在 Touches 中获取 SKSpriteNode 的属性

ios - 处理我希望能够引用的 10k 字典的最佳方法?