我有一个在JSON查询中接收它的数组,需要按字母顺序对数组进行排序。
我设法按字母顺序对数组进行排序,但我无法将此数组拆分为多个部分。
我找到了一个NSDicctionary的例子,但我不知道如何填写它。提前谢谢!
animals = @{@"B" : @[@"Bear", @"Black Swan", @"Buffalo"],
@"C" : @[@"Camel", @"Cockatoo"],
@"D" : @[@"Dog", @"Donkey"],
@"E" : @[@"Emu"],
@"G" : @[@"Giraffe", @"Greater Rhea"],
@"H" : @[@"Hippopotamus", @"Horse"],
@"K" : @[@"Koala"],
@"L" : @[@"Lion", @"Llama"],
@"M" : @[@"Manatus", @"Meerkat"],
@"P" : @[@"Panda", @"Peacock", @"Pig", @"Platypus", @"Polar Bear"],
@"R" : @[@"Rhinoceros"],
@"S" : @[@"Seagull"],
@"T" : @[@"Tasmania Devil"],
@"W" : @[@"Whale", @"Whale Shark", @"Wombat"]};
答案 0 :(得分:2)
如果这是你回来的阵列
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;
}