NSPredicate to assist counting objects in array
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];
}
精彩评论