在tableview中帮助w /一系列字典

时间:2010-07-29 17:59:22

标签: iphone uitableview nsarray nsdictionary nspredicate

这有点令人困惑所以请耐心等待。

我有一个字典数组(listOfStates)。 listOfStates具有以下结构:

{stateName} - {stateCapital}
{Alabama} - {Montgomery}
{Alaska} - {Juneau}
{Arizona} - {Phoenix}
...
{West Virginia} - {Charleston}
{Wisconsin} - {Madison}
{Wyoming} - {Cheyenne}

这是用于获取每个美国州(州名称)的第一个字母的代码,以便按字母顺序将它们组合在一起:

listOfStates = [[NSArray alloc] init];  
stateIndex = [[NSMutableArray alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];

for (NSDictionary *row in listOfStates) {
    [tempArray addObject:[row valueForKey:@"stateName"]];

     for (int i=0; i<[tempArray count]-1; i++){
     char alphabet = [[tempArray objectAtIndex:i] characterAtIndex:0];
     NSString *uniChar = [NSString stringWithFormat:@"%C", alphabet];
         if (![stateIndex containsObject:uniChar]){  
             [stateIndex addObject:uniChar];
         }
     }
}

该代码工作得非常漂亮,但是我在使用NSPredicate来理解如何使用 BOTH @“stateName”和@“stateCapital”(作为副标题)填充tableview单元格时遇到问题对数组进行排序。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
    //---get the letter in the current section---
NSString *alphabet = [stateIndex objectAtIndex:[indexPath section]];

    //---get all states beginning with the letter---
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
NSArray *states = [[listOfStates valueForKey:@"stateName"] filteredArrayUsingPredicate:predicate];

        //---extract the relevant state from the states object---
    cell.textLabel.text = [states objectAtIndex:indexPath.row];
        //cell.textLabel.text = [[listOfStates objectAtIndex:indexPath.row] objectForKey:@"stateName"];
        //cell.detailTextLabel.text = [[listOfStates objectAtIndex:indexPath.row] objectForKey:@"stateCapital"];

return cell;
}

我们非常感谢您的帮助,如果您认为它有助于您理解,我非常愿意发送整个项目。

非常感谢你。

2 个答案:

答案 0 :(得分:1)

cell.textLabel.text = [[states objectAtIndex:indexPath.row] objectForKey:@"stateName"];
cell.detailTextLabel.text =[states objectAtIndex:indexPath.row] objectForKey:@"stateCapital"];

更新

  

不幸的是,只有'状态'数组   包括州名......

将谓词和过滤器更改为:

NSPredicate *p=[NSPredicate predicateWithFormat:@"stateName beginswith[c] %@", alphabet];
NSArray *states=[listOfStates filteredArrayUsingPredicate:p];

...这将为您提供一系列状态,所有状态都以相同的字母开头。然后你可以对数组进行排序,行将为你提供正确的状态字典。

答案 1 :(得分:0)

可能更改数据结构,因此您有一个字典,其中州名称为键,州首府为值。这样,您可以使用键对键进行排序并获取值,而不是索引。