我终于把它做好了。这是我的viewdidload方法的代码。这可能不是最干净的方法来获得我的结果,但它工作得很好!不过,我欢迎任何建议。
- (void)viewDidLoad {
[super viewDidLoad];
// Load the UICustomTabViewController
UICustomTabViewController *tvController = [[UICustomTabViewController alloc]
initWithNibName:@"TabViewController" bundle:nil];
self.tabViewController = tvController;
[tvController release];
YourAppDelegate *AppDelegate = (YourAppDelegate *)[[UIApplication
sharedApplication] delegate];
// Create an array sorted by CommonName of the AppDelegate.data
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"CommonName" ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [[AppDelegate.data objectForKey:@"Rows"] sortedArrayUsingDescriptors:sortDescriptors];
// Now set tableDataSource equal to sortedArray
self.tableDataSource = sortedArray;
// Create a set of the first letters used by the strings in CommonName and sort them
NSMutableSet *firstCharacters = [NSMutableSet setWithCapacity:0];
for( NSString *string in [tableDataSource valueForKey:@"CommonName"] )
[firstCharacters addObject:[string substringToIndex:1]];
self.arrayOfInitialLetters = [[firstCharacters allObjects]
sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
self.sectionedDictionaryByFirstLetter = [NSMutableDictionary dictionary];
// All data sorted in sections by initial letter of "CommonName"
NSDictionary *eachItemList; //PUTS ALL THE DATA FOR EACH ITEM IN IT'S OWN SECTION
for (eachItemList in tableDataSource) //eachElementList is an array with a section for each item
{
NSDictionary *aDictionary = [[NSDictionary alloc] initWithDictionary:eachItemList];
NSString *firstLetterString;
firstLetterString = [[aDictionary valueForKey:@"CommonName"]substringToIndex:1];
NSMutableArray *existingArray;
if (existingArray = [sectionedDictionaryByFirstLetter valueForKey:firstLetterString])
{
[existingArray addObject:eachItemList];
} else {
NSMutableArray *tempArray = [NSMutableArray array];
[sectionedDictionaryByFirstLetter setObject:tempArray forKey:firstLetterString];
[tempArray addObject:eachItemList];
}
[aDictionary release];
[eachItemList release];
NSLog(@"nameIndexesDictionary:%@", sectionedDictionaryByFirstLetter);
}
这就是我在cellForRowatindexPath方法中获得正确行的方法
NSInteger section = [indexPath section];
NSString *key = [arrayOfInitialLetters objectAtIndex:section];
NSArray *nameSection = [sectionedDictionaryByFirstLetter objectForKey:key];
NSDictionary *dictionary = [nameSection objectAtIndex:indexPath.row];