Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Created April 22, 2010 15:55
Show Gist options
  • Select an option

  • Save lukeredpath/375409 to your computer and use it in GitHub Desktop.

Select an option

Save lukeredpath/375409 to your computer and use it in GitHub Desktop.
A small NSArray category for producing indexed arrays of objects for use with UITableView sections
//
// NSArray+Indexing.h
// TellYouGov
//
// Created by James Adam on 16/02/2010.
// Copyright 2010 Lazyatom Limited. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface NSArray (Indexing)
- (NSArray *)indexUsingCollation:(UILocalizedIndexedCollation *)collation withSelector:(SEL)selector;
@end
@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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment