puppybits
puppybits

Reputation: 1110

NSFetchedResultsController Creating Sections

When using the NSFetchedResultsController to create section headers for the UITableViewController the fetchedResultsController.sections has an object for each item not each section.

//Set up the request
NSManagedObjectContext *context = self.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

[fetchRequest setEntity:[NSEntityDescription entityForName:@"Person" 
                                    inManagedObjectContext:context]];

[fetchRequest setFetchBatchSize:20];

NSSortDescriptor *sortDescriptor = nil;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" 
                                             ascending:YES];
NSArray *sortDescriptors = nil;
sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[sortDescriptor release]; sortDescriptor = nil;

[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptors release]; sortDescriptors = nil;

//setup fetch results controller
NSFetchedResultsController *controller = nil;
controller = [[NSFetchedResultsController alloc] 
              initWithFetchRequest:fetchRequest 
              managedObjectContext:context 
                sectionNameKeyPath:@"firstName" 
                         cacheName:@"PersonCache"];

__fetchedResultsController = controller;

[fetchRequest release]; fetchRequest = nil;

//IMPORTANT: Delete cache before changing predicate
[NSFetchedResultsController deleteCacheWithName:nil]; 
NSError *error = nil;
if (![controller performFetch:&error])
{
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
} else if ([[controller fetchedObjects] count] == 0){
    [self retrievePeoples];
}

NSLog(@"result count: %i", [[controller fetchedObjects] count]);
NSLog(@"section count: %i", [[controller sections] count]);
NSLog(@"sectionIndexTitles count: %i", [[controller sectionIndexTitles] count]);

This returns:

result count: 18
section count: 18
sectionIndexTitles count: 13

Shouldn't the section count and the sectionIndexTitles count match? When the numberOfSectionsInTableView: and tableView:numberOfRowsInSection: methods are called I should just be able to look to the fetchedResultsController.section for a count without any additional sorting.

How do I setup the NSFetchResultsController properly to have each object in the sections array be for per section and not for all objects?

Upvotes: 1

Views: 866

Answers (1)

puppybits
puppybits

Reputation: 1110

This was answered by Phillip Mills on another forum. The problem was I was using the entire firstName to create sections (not just the first letter). The fix is to update the entity to create the a section title whenever updated or changed. Apple's DateSectionTitles has a sample of what to do.

Upvotes: 2

Related Questions