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.
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With