带多个键的NSDictionary到TableView



我正在开发一个iOS应用程序,它将列出我存储在NSDictionary中的一些数据。我将使用表视图来做到这一点,但有一些问题,我应该如何开始。

数据看起来像这样:

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;
    }
);

我试图将所有"类别"值作为表中的一个部分,并将每个"描述"中的"名称"放在正确的部分中。正如我所提到的,不确定如何从这里开始,我如何为每个"类别"获得一个新的部分?

您"只需要"实现表视图数据源方法来提取信息从你的字典:-)

如果self.dict是上面的字典,那么self.dict[@"category"]是一个包含每节一本字典。因此(使用"现代Objective-C下标语法"):

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

对于每个section,

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

是一个数组,每行包含一个字典。因此:

- (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;
}

最新更新