问题描述
这有点令人困惑,所以请忍受我.
This is kinda confusing so please bear with me.
我有一个字典数组(listOfStates).其中listOfStates具有以下结构:
I have an array (listOfStates) of dictionaries. Where listOfStates has this structure:
{stateName} - {stateCapital}
{Alabama} - {Montgomery}
{Alaska} - {Juneau}
{Arizona} - {Phoenix}
...
{West Virginia} - {Charleston}
{Wisconsin} - {Madison}
{Wyoming} - {Cheyenne}
这是用于获取每个美国州(州名)的第一个字母以便将它们按字母顺序组合在一起的代码:
This is the code used to obtain the 1st letter of each US State(stateName) in order to group them together alphabetically:
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"(作为字幕)填充表格视图单元时遇到了问题对数组进行排序.
That code works beautifully, however I'm having issues understanding how to populate a tableview cell with BOTH the @"stateName" and @"stateCapital"(as the subtitle) after I use NSPredicate to sort the array.
-(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;
}
感谢您的帮助,如果您认为这会帮助您理解,我将非常乐意发送整个项目.
Any help is appreciated and I am more than willing to send the entire project, if you think it'll help you understand.
非常感谢.
推荐答案
也许更改数据结构,以便您拥有一本以州名作为关键字,以州大写字母作为值的字典.这样,您可以对键进行排序并使用键而不是索引来获取值.
Maybe change the data structure so you have one dictionary with state name as a key and state capital as a value. That way you can sort your keys and get the value using the keys, not indexes.
这篇关于在表视图中使用字典数组帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!