1

私は自分の中に入れる必要があるこのデータを持っていますが、UITableViewそれを適切に実装する方法について混乱しています。値を適切に分離して、Boys データを Girls データに分離することができません。

{
"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

混乱しているので、データを細かく分割してください。セクションごとに 1 つずつ、合計 2 つの配列が必要です。したがって、男の子の名前の配列と女の子の名前の別の配列が必要です。

これは、埋め込まれた 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]]; 
     }

これで、テーブル セクションごとに 1 つずつ、合計 2 つの配列が作成されました。セクションの配列を作成し、これらの配列をそれに入れます。

    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 に答える