situation: CoreData db with “contacts” entities and “Sum” attribute (positive or negative or 0)
goal: tableviewcontroller with 3 sections, 1st positive 2nd negative 3rd (zero) “ARCHIVED”
so far: sort descrpitor with @selector(compare:) (without predicate because list of all contacts wanted)
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Contact"];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"moneySum" ascending:YES selector:@selector(compare:)]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.database.managedObjectContext
sectionNameKeyPath:@"sectionName"
cacheName:nil];
and in a Category for Contact Entity:
- (NSString *)sectionName {
[self willAccessValueForKey:@"sectionName"];
NSString *sectionName;
double value = [[self valueForKey:@"moneySum"] doubleValue];
if (value > 0) sectionName = POS_SECTION;
else if (value < 0) sectionName = NEG_SECTION;
else sectionName = ARCHIVE_SECTION;
[self didAccessValueForKey:@"sectionName"];
return sectionName;
}
I do get 3 categories now, but it obviously sorts them with archive in the middle, not at the end.
I thought about adding a second sortDescriptor to the sortDescriptors array (before compare: one) but the most intuitive way for me (isEqualToNumber:) obviously doesn’t work because i can’t specify any arguments (@selector ( ..:) ) or am I wrong?
Sorry, quite new to this whole coding thing 🙂
From the “Core Data Programming Guide”:
This means that you cannot use a custom sort descriptor in your fetch request. You must store an additional (non-transient) attribute in the entity, for example “0”, “1”, “2” for positive/negative/zero sums.
You can then use this attribute for both the sort descriptor and for the
sectionNameKeyPath, you don’t need a transient attribute “sectionName”.The mapping from “0”, “1”, “2” to the actual section header is then done in
tableView:titleForHeaderInSection:.