Q:

UITableView grouping sections

I have a UITableView that's populated using core data & sqlite.
I'd like to have sections grouped in the UITableView based on an attribute from the database table. 
e.g If i had a category field in the database table called "type", what would be the best way of sectioning that data out?
I've seen examples using arrays, but I'm getting stuck with the core data. all the data is currently displayed from the database and I'd like to section it out somehow.
thanks in advance.

A:

If you are using an NSFetchedResultsController to fetch your results and connect them to your UI it's pretty easy. Just set the sectionNameKeyPath: parameter of the initWithFetchRequest call to NSFetchedResultsController.
In this example, which is only slightly modified from the class reference for NSFetchedResultsController I have defined a key path that will use the section named "group" as the section title. Thus, if you have rows in your database that have a group set to "Cats" and other rows with a group set to "Dogs" your resulting table view will have 2 sections - one for cats and one for dogs.
NSManagedObjectContext *context = <#Managed object context#>;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Configure the request's entity, and optionally its predicate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"<#Sort key#>" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];

NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
        initWithFetchRequest:fetchRequest
        managedObjectContext:context
        sectionNameKeyPath:@"groups"
        cacheName:@"<#Cache name#>"];
[fetchRequest release];

NSError *error;
BOOL success = [controller performFetch:&error];

For more information about key-paths you have to search for the key path documentation in the Xcode doc set. For simple cases though, it's just the name of an attribute of your returned objects.

