Reputation: 1309
I am using NSFetchedResultsController to populate the tableView of my application it is group by section(in which case a category property in my core data object) I want to reorder the section manually not by alphabet order.
below is the code of what I have done so far
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Media" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:@"category" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:_context sectionNameKeyPath:@"category"
cacheName:@"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
Thanks in advance!
Upvotes: 2
Views: 709
Reputation: 6505
You can add a new entity named MediaCategory
with:
name
rank
media
to the entity Media
and replace the category
attribute with a relationship to MediaCategory
.
Then, you can sort the request's result with the following sorts descriptors:
fetchRequest.sortDescriptors =
[NSArray arrayWithObjects:
[[NSSortDescriptor alloc] initWithKey:@"category.rank" ascending:NO],
[[NSSortDescriptor alloc] initWithKey:@"category.name" ascending:NO], // required only if many categories have the same rank
nil];
and provide @"category.name"
as the result controller's sectionNameKeyPath
.
Upvotes: 2
Reputation: 424
If the task is to provide the custom order of sections, than you can subclass NSFetchedResultsController and implement
- (NSInteger)sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)sectionIndex;
and, if needed
@property (nonatomic, readonly) NSArray *sectionIndexTitles;
- (NSString *)sectionIndexTitleForSectionName:(NSString *)sectionName;
Upvotes: 2