如果這是你回來
NSArray* animals = @[@"Bear", @"Black Swan", @"Buffalo",@"Camel", @"Cockatoo",@"Dog", @"Donkey",@"Emu",@"Giraffe", @"Greater Rhea",@"Hippopotamus", @"Horse",@"Koala",@"Lion", @"Llama",@"Manatus", @"Meerkat",@"Panda", @"Peacock", @"Pig", @"Platypus", @"Polar Bear",@"Rhinoceros",@"Seagull",@"Tasmania Devil",@"Whale", @"Whale Shark", @"Wombat"];
你可以做這樣的事情來獲取字典
NSArray* alphabets = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
NSMutableDictionary* indexedAnimals = [NSMutableDictionary dictionary];
for (NSString* letter in alphabets)
{
NSArray* filteredAnimals = [animals filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSString* evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject hasPrefix:letter];
}]];
if ([filteredAnimals count])
{
indexedAnimals[letter] = filteredAnimals;
}
}
NSArray* sectionLetters = [[indexedAnimals allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
然後配置表視圖陣列
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [sectionLetters count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return sectionLetters[section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [indexedAnimals[sectionLetters[section]] count]
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellId" forIndexPath:indexPath];
NSString *animal = indexedAnimals[sectionLetters[indexPath.section]][indexPath.row];
cell.textLabel.text = animal;
return cell;
}
你想用這本詞典做什麼? – abhi1992
對不起rmaddy,我想知道爲什麼「iphone」和「xcode」標籤與你認爲 – garatu
這個問題關係不大,特別是關於tableview和nsdictionary的問題。你的問題並沒有解決iphone/xcode的問題。因此相關性很差! –