First Letter Section Headers with Core Data
Posted
by Cory Imdieke
on Stack Overflow
See other posts from Stack Overflow
or by Cory Imdieke
Published on 2010-03-15T20:53:19Z
Indexed on
2010/03/15
22:09 UTC
Read the original article
Hit count: 422
core-data
|iphone-sdk-3.0
I'm trying to create a list of people sorted in a tableView of sections with the first letter as the title for each section - a la Address Book. I've got it all working, though there is a bit of an issue with the sort order. Here is the way I'm doing it now:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Contact" inManagedObjectContext:context]];
NSSortDescriptor *fullName = [[NSSortDescriptor alloc] initWithKey:@"fullName" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:fullName, nil];
[request setSortDescriptors:sortDescriptors];
[fullName release];
[sortDescriptors release];
NSError *error = nil;
[resultController release];
resultController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:@"firstLetter" cacheName:nil];
[resultController performFetch:&error];
[request release];
fullName is a standard property, and firstLetter is a transient property which returns - as you'd expect - the first letter of the fullName. 95% of the time, this works perfectly.
The problem is the result controller expects these two "lists" (the sorted fullName list and the sorted firstLetter list) to match exactly. If I have 2 contacts like John and Jack, my fullName list would sort these as Jack, John every time but my firstLetter list might sort them as John, Jack sometimes as it's only sorting by the first letter and leaving the rest to chance. When these lists don't match up, I get a blank tableView with 0 items in it.
I'm not really sure how I should go about fixing this issue, but it's very frustrating. Has anyone else run into this? What did you guys find out?
© Stack Overflow or respective owner