Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split NSArray into alphabetical sections for use with index tableview

I have a NSArray that I have parsed and sorted alphabetically from some xml I am getting from my database. I am now wondering how to split this array up for use with a index on a tableview for quicker searching.

Where my table gets a bit different is that it dosn't alway use the whole alphabet, and unlike most examples I have found the dataset I use varies alot from day to day..

so I am trying to figure out how to split a sorted array into alphabetical sections that are not always the same.

As cocofu pointed out, Yes I have got my sectionIndexTitlesForTableView already implemented, I am now trying to split my nsarray into sections so that scrolling works with sectionIndexTitlesForTableView.

like image 744
C.Johns Avatar asked Feb 22 '23 22:02

C.Johns


2 Answers

I would create an NSSet with the first letters you use in your array and then create a sorted array from that. Assuming all of the first letters are of the correct case, it would look something like:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView 
{
   NSMutableSet *mySet = [[[NSMutableSet alloc] init] autorelease];
   for ( NSString *s in myArray )
   {
     if ( s.length > 0 )
       [mySet addObject:[s substringToIndex:1]];
   }

   NSArray *indexArray = [[mySet allObjects] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
   return indexArray;
}
like image 73
EricS Avatar answered May 01 '23 19:05

EricS


You could use an NSPredicate to derive the data like so:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH 'a'"];
NSArray *aElements = [myArray filterUsingPredicate:predicate];

I would love to hear of a more efficient way instead of looping or having 26 NSPredicate Statements being run for every letter of the Alphabet or doing a loop with the characters and returning the elements.

You could store each filtered array in an NSDictionary with all the letters of the alphabet as the keys and then retrieve it later and check if it's empty (which means it has no elements for that letter). I believe BEGINSWITH is Case-Sensitive

like image 38
Suhail Patel Avatar answered May 01 '23 19:05

Suhail Patel