0

这有点令人困惑,所以请多多包涵。

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

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

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

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 对数组进行排序后,我无法理解如何使用 @"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;
}

任何帮助表示赞赏,如果您认为它会帮助您理解,我非常愿意发送整个项目。

非常感谢。

4

2 回答 2

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

更新:

不幸的是,'states' 数组只包含州名......

将谓词和过滤器更改为:

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

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

于 2010-07-29T18:40:45.433 回答
0

也许改变数据结构,这样你就有一个字典,其中状态名称作为键,状态资本作为值。这样,您可以对键进行排序并使用键而不是索引来获取值。

于 2010-07-30T12:57:25.117 回答