Created
April 22, 2010 15:55
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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