开发者

NSPredicate to assist counting objects in array

开发者 https://www.devze.com 2023-01-22 08:33 出处:网络
I have an array containing dictionaries, and I want to show the values in a table view according to the \"name\" field in each dictionary. Suppose the name starts with \"a\"; then \"b\" and \"c\" are

I have an array containing dictionaries, and I want to show the values in a table view according to the "name" field in each dictionary. Suppose the name starts with "a"; then "b" and "c" are in different sections. The number of sections corresponds to the "name" field of the dictionaries. How do I get the number of rows? If any one knows, please give the solution.

- (NSInteger)tableView:(UITableView开发者_Go百科 *)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];
}


You need to have the state names in an array in order to filter them with a predicate.

Try this:

...
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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号