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"(サブタイトルとして)の両方を入力する方法を理解するのに問題があります。

-(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

データ構造を変更して、州名をキー、州都を値とする辞書を 1 つ持つようにします。そうすれば、インデックスではなくキーを使用してキーをソートし、値を取得できます。

于 2010-07-30T12:57:25.117 に答える