1

我有这些数据需要放入其中,UITableView但我对如何正确实施它感到困惑。我无法正确分离这些值以将男孩数据与女孩数据分开。

{
"QUERY": {
    "COLUMNS": [
        "NAME",
        "GENDER"
    ],
    "DATA": [
    [
        "Anne",
        "Girl"
    ],
    [
        "Alex",
        "Boy"
    ],
    [
        "Vince",
        "Boy"
    ],
    [
        "Jack",
        "Boy"
    ],
    [
        "Shiela",
        "Girl"
    ],
    [
        "Stacy",
        "Girl"
    ]
  ]
},
"TOTALROWCOUNT": 6
}

我有这个代码:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [genderArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [genderArray objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [namesArray count];
}

namesArray 包含 NAME 返回的所有值,而 genderArray 包含 GENDER 的所有值。我越来越糊涂了。

4

1 回答 1

6

当您感到困惑时,请将您的数据分解成碎片。您需要两个数组,每个部分一个。所以你想要一组男孩的名字,和另一组女孩的名字。

您可以通过迭代嵌入的 DATA 数组来获得它。

将您的数据转换为 NSDictionary 对象。你的数据看起来像 JSON 所以......

    NSDictionary* myDict =  [NSJSONSerialization JSONObjectWithData:myJsonData 
                                                            options:0 error:&error];

提取数据...

    NSArray* dataArray = [myDict objectForKey:@"DATA"];

迭代...

    NSMutableArray* boys = [[NSMutableArray alloc] init];
    NSMutableArray* girls = [[NSMutableArray alloc] init];
    for (id person in dataArray) {
         if ([[person objectAtIndex:1] isEqualToString:@"Girl"])
              [girls addObject:[person objectAtIndex:0]];
         else [boys  addObject:[person objectAtIndex:0]]; 
     }

现在您有两个数组,一个用于每个表格部分。制作一个部分数组,并将这些数组放入其中:

    NSArray* sections = [NSArray arrayWithObjects:boys,girls,nil];

为您的节标题创建一个单独的数组:

    NSArray* headers = [NSArray arrayWithObjects:@"Boys",@"Girls",nil];

现在您的数据源方法如下所示:

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return [sections count];
    }

    - (NSString *)tableView:(UITableView *)tableView 
    titleForHeaderInSection:(NSInteger)section
    {
        return [headers objectAtIndex:section];
    }

    - (NSInteger)tableView:(UITableView *)tableView 
     numberOfRowsInSection:(NSInteger)section
    {
        return [[sections objectAtIndex:section] count];
    }

最后

- (UITableViewCell *)tableView:(UITableView *)tableView 
          cellForRowAtIndexPath:(NSIndexPath *)indexPath

    ...

       cell.textLabel.text = (NSString*)[[self.sections objectAtIndex:indexPath.section]   
                                                        objectAtIndex:indexPath.row];
于 2013-01-20T03:23:05.067 回答