首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有指向TableView的多个密钥的NSDictionary

具有指向TableView的多个密钥的NSDictionary
EN

Stack Overflow用户
提问于 2013-04-13 20:31:35
回答 1查看 1.5K关注 0票数 0

我正在开发一个iOS应用程序,它将列出我存储在NSDictionary中的一些数据。我将使用表视图来执行此操作,但遇到了一些如何启动的问题。

数据看起来像这样:

代码语言:javascript
复制
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;
    }
);

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-13 21:20:19

您“只需”实现表视图数据源方法来从字典中提取信息:-)

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

代码语言:javascript
复制
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.dict[@"category"] count];
}

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

对于每个部分,

代码语言:javascript
复制
self.dict[@"category"][section][@"description"]

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

代码语言:javascript
复制
- (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;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15987820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档