0

NSDictionary に保存したデータを一覧表示する iOS アプリケーションに取り組んでいます。これを行うためにテーブル ビューを使用しますが、開始方法に問題があります。

データは次のようになります。

category =     (
            {
        description =             (
                            {
                id = 1;
                name = Apple;
            },
                            {
                id = 5;
                name = Pear;
            },
                            {
                id = 12;
                name = Orange;
            }
        );
        id = 2;
        name = Fruits;
    },
            {
        description =             (
                            {
                id = 4;
                name = Milk;
            },
                            {
                id = 7;
                name = Tea;
            }
        );
        id = 5;
        name = Drinks;
    }
);

すべての「カテゴリ」値をテーブルのセクションとして、各「説明」の「名前」を正しいセクションに入れようとしています。前述したように、ここから始める方法がわからないのですが、「カテゴリ」ごとに新しいセクションを取得するにはどうすればよいですか?

4

1 に答える 1

2

ディクショナリから情報を抽出するには、テーブル ビュー データソース メソッドを実装する必要があります :-)

self.dictが上記の辞書の場合、self.dict[@"category"]はセクションごとに 1 つの辞書を含む配列です。したがって (「最新の Objective-C 添え字構文」を使用):

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.dict[@"category"] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.dict[@"category"][section][@"name"];
}

セクションごとに、

self.dict[@"category"][section][@"description"]

行ごとに 1 つの辞書を含む配列です。したがって:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dict[@"category"][section][@"description"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    NSString *name = self.dict[@"category"][indexPath.section][@"description"][indexPath.row][@"name"];
    cell.textLabel.text = name;
    return cell;
}
于 2013-04-13T13:20:18.977 に答える