NSPredicate以协助计算数组中的对象

时间:2010-10-27 10:40:38

标签: objective-c cocoa-touch uitableview nspredicate

我有一个包含字典的数组,我想根据每个字典中的“name”字段在表视图中显示这些值。假设名称以“a”开头;那么“b”和“c”在不同的部分。部分的数量对应于字典的“名称”字段。我如何获得行数?如果有人知道,请给出解决方案。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    //---get the letter in each section; e.g., A, B, C, etc.---
    NSString *alphabet = [subscribeIndexArray objectAtIndex:section];

    //---get all states beginning with the letter---

    //NSMutableArray *states =[[NSMutableArray alloc]init];
    NSArray *states;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];

    for(NSDictionary *dict in subscribeViewArray1)
    {
       states =[[dict valueForKey:@"name"] filteredArrayUsingPredicate:predicate];
    }

    //---return the number of states beginning with the letter---
    return [states count];
}

1 个答案:

答案 0 :(得分:1)

您需要在数组中包含状态名称,以便使用谓词对其进行过滤。

试试这个:

...
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
NSMutableArray *matchingStatesArray = [[NSMutableArray alloc] init];
for (NSDictionary *dict in subscribeViewArray1) {
       //get the state names in an array
    [matchingStatesArray addObject:[dict objectForKey:@"name"]];
    }
    [matchingStatesArray filterUsingPredicate:predicate];

    return [[matchingStatesArray autorelease] count];
}