My app use CoreData. It has a UISegmentedControl and a tableview. The UISegmentedControl is used to update tableview based on different criteria.
The 1st option of UISegmentedControl will show all data in a single tableview section. So I use the following code in - (NSFetchedResultsController*)fetchedResultsController
frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:[self managedObjectContext]
sectionNameKeyPath:nil
cacheName:@"Root"];
The 2nd option will show data in multiple tableview section. So I need NSSortDescriptor and set sectionNameKeyPath.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"city"
ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *frc = nil;
frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:[self managedObjectContext]
sectionNameKeyPath:@"city"
cacheName:@"Root"];
Because sectionNameKeyPath is different which each of them need different NSSortDescriptor, I assume I need two different NSFetchedResultsController.
The code I use to reload tableview:
- (void) touchDownAtSegmentIndex:(NSUInteger)segmentIndex{
NSPredicate *predicate;
NSError *error;
[NSFetchedResultsController deleteCacheWithName:@"Root"];
if(segmentIndex == 0)
{
}
else if(segmentIndex == 1)
{
}
else
{
return;
}
[[[self fetchedResultsController] fetchRequest] setPredicate:predicate];
[[self fetchedResultsController] performFetch:&error];
[[self tableView] reloadData];
}
Anyone can provide me a sample of code that use two NSFetchedResultsController. Thank you.
SOLUTION:
In addition from @iTukker idea, I added more checking before returning fetchedResultsController
. Without this checking, this method will return fetchedResultsController
instead of executing switch .. case ..
statement.
- (NSFetchedResultsController*)fetchedResultsController {
.....
if ((fetchedResultsController!= nil) && [self.segmentChanged isEqualToString:@"false"])
return fetchedResultsController;
.....
if (frc == nil) {
switch (segmentendControl.selectedSegmentIndex) {
case 0: {
frc = ... //first frc
[frc retain];
break;
}
case 1: {
frc = ... //second frc
[frc retain];
break;
}
}
}
....
}