//汉字索引
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"plist"];
NSArray *cities = [NSArray arrayWithContentsOfFile:path];
self.keys = [[[NSMutableArray alloc]init]autorelease];
//创建26个可变数组
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
for (char character = 'a'; character <= 'z'; character++) {
NSMutableArray *array = [[NSMutableArray alloc]init];
[dic setObject:array forKey:[NSString stringWithFormat:@"%c",character]];
[array release];
[self.keys addObject:[NSString stringWithFormat:@"%c",character]];
}
//将数据按拼音首字母分别放入数组
for (NSString *city in cities) {
//获取拼音首字母
NSString *initial = [NSString stringWithFormat:@"%c",pinyinFirstLetter([city characterAtIndex:0])];
NSMutableArray *array = [dic objectForKey:initial];
[array addObject:city];
}
//将空组去掉
for (char character = 'a'; character <= 'z'; character++) {
NSString *key = [NSString stringWithFormat:@"%c",character];
NSArray *array = [dic objectForKey:key];
if (!array.count) {
[dic removeObjectForKey:key];
}
}
self.keys = [[dic.allKeys sortedArrayUsingSelector:@selector(compare:)] mutableCopy];
//self.keys = [[dic allKeys] mutableCopy];;
self.list = dic;
[dic release];
}
//显示索引行
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return self.keys;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:@"sortednames" ofType:@"plist"];
self.names = [NSDictionary dictionaryWithContentsOfFile:path];
self.keys = [self.names allKeys];
//将key按照字母表升序排列
self.keys = [self.keys sortedArrayUsingSelector:@selector(compare:)];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)dealloc{
[super dealloc];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.names.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *currentKey = [self.keys objectAtIndex:section];
NSArray *currentGroup = [self.names objectForKey:currentKey];
return currentGroup.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
}
NSString *currentKey = [self.keys objectAtIndex:indexPath.section];
NSArray *currentGroup = [self.names objectForKey:currentKey];
NSString *currentName = [currentGroup objectAtIndex:indexPath.row];
cell.textLabel.text = currentName;
return cell;
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return self.keys;
}