Лучший способ справиться с этим - использовать инструменты, предоставляемые фреймворком. В этом случае вы хотите использовать UILocalizedIndexedCollation (ссылка для разработчика).
У меня также есть декоратор для этого класса, который предназначен для вставки значка {{search}} для вас и обработки смещений. Это аналог замены для UILocalizedIndexedCollation.
Я опубликовал более подробное описание того, как использовать это в своем блоге . Декоратор доступен здесь (Gist).
Основная идея состоит в том, чтобы сгруппировать вашу коллекцию в массив массивов, где каждый массив представляет раздел. Вы можете использовать UILocalizedIndexedCollation
(или мою замену), чтобы сделать это. Вот небольшой метод NSArray
категории, который я использую для этого:
@implementation NSArray (Indexing)
- (NSArray *)indexUsingCollation:(UILocalizedIndexedCollation *)collation withSelector:(SEL)selector;
{
NSMutableArray *indexedCollection;
NSInteger index, sectionTitlesCount = [[collation sectionTitles] count];
indexedCollection = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
for (index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *array = [[NSMutableArray alloc] init];
[indexedCollection addObject:array];
[array release];
}
// Segregate the data into the appropriate section
for (id object in self) {
NSInteger sectionNumber = [collation sectionForObject:object collationStringSelector:selector];
[[indexedCollection objectAtIndex:sectionNumber] addObject:object];
}
// Now that all the data's in place, each section array needs to be sorted.
for (index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *arrayForSection = [indexedCollection objectAtIndex:index];
NSArray *sortedArray = [collation sortedArrayFromArray:arrayForSection collationStringSelector:selector];
[indexedCollection replaceObjectAtIndex:index withObject:sortedArray];
}
NSArray *immutableCollection = [indexedCollection copy];
[indexedCollection release];
return [immutableCollection autorelease];
}
@end
Итак, учитывая массив объектов, например books
, который я хочу разделить на разделы на основе их имени (класс Book
имеет метод name
), я бы сделал это:
NSArray *books = [self getBooks]; // etc...
UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
NSArray *indexedBooks = [books indexUsingCollation:collation withSelector:@selector(name)];