在cellForRowAtIndexPath中循环遍历一组字典

时间:2011-09-15 12:25:27

标签: iphone tableview

我有一系列词典。每个字典都有一个类别。我想用一个共同的类别的所有词典填充tableview,这是在之前的tableview中选择的。

NSDictionary *name = [sortedNames objectAtIndex:indexPath.row];
NSMutableString *currentCat = [name objectForKey:@"category"];

if ([currentCat isEqualToString:catSelected]) {
    cell.textLabel.text = [name objectForKey:@"title"];
}

正如您可能已经猜到的那样,如果阵列中的前两个词典不是所选类别的,但第三个是,那么第三个得到了充实。

我如何以正确的方式解决这个问题?

2 个答案:

答案 0 :(得分:1)

在.h文件中获取一个可变数组在viewWillAppear init中,使用你的代码添加该数组的对象,如

  array = [[NSMutableArray alloc] init];
for(int i = 0;i<[sortedNames count];i++)
{
    NSDictionary *name = [sortedNames objectAtIndex:i];
    NSMutableString *currentCat = [name objectForKey:@"category"];

    if ([currentCat isEqualToString:catSelected]) {
        [array addObject:[name objectForKey:@"title"]];
    }
}

在numberOfRowsInSection方法中给出

[array count];

在cellForRowAtIndexPath方法

cell.textLabel.text =[array objectAtIndex:indexPath.row];

答案 1 :(得分:1)

您可以在加载视图控制器时构建NSMutableArray。此数组仅包含要在该表视图中显示的对象。

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.namesArray = [NSMutableArray array];
    for (NSDictionary *dict in sortedNames) {
        if ([(NSString *)[dict objectForKey:@"category"] isEqualToString:catSelected]) {
            [newArray addObject:dict];
        }
    }
}


然后,在tableView:cellForRowAtIndexPath:中,根据索引分配:

if (indexPath.row < [namesArray count]) {    // Just incase...
    cell.textLabel.text = [namesArray objectAtIndex:indexPath.row];
}

这里的关键思想是我们不会为表格视图提供我们不需要的数据。

相关问题