1

Suppose a table named testTable:

(NSNumber*) numValue
(NSString*) stringValue

Then suppose about 50 records in it. numValue different in every record. If I create NSFetchedResultController like this:

NSFetchRequest *request = [[NSFetchedResultsController alloc] 
                            initWithFetchRequest: request 
                            managedObjectContext: context 
                            sectionNameKeyPath: @"numValue" 
                            cacheName: @"testTable"]];

I'll get 50 sections then.

My question is: How can I get 2 sections: First containing records with numValue less than some x and second with records where numValue bigger than the same x.

For x = 15 it could look like this:

NSFetchRequest *request = [[NSFetchedResultsController alloc] 
                            initWithFetchRequest: request 
                            managedObjectContext: context 
                            sectionNameKeyPath: @"numValue > 15" 
                            cacheName: @"testTable"]];

Possible solutions are:

  1. We can edit our Entity as @Dima said.
  2. In the numberOfSectionsInTableView: we can just look at the section names and compare them to x. Then we could look at these names in tableView:numberOfRowsInSection: and calculate what we need to. But that's feels dirty too. Better than first approach, but still.

UPDATE: Well, I've almost figured out 3rd way to do that. Thanks to the @Dima's link. Here is the code:

[self setFetchedResultsController: [[NSFetchedResultsController alloc]
    initWithFetchRequest: request 
    managedObjectContext: context 
    sectionNameKeyPath: [NSString stringWithFormat: @"numValue.compare(%f)", x]];

But there is a problem with KVC compliance: methods(selectors) with arguments aren't KVC compliant obviously. Any idea for workaround?

folex
  • 5,122
  • 1
  • 28
  • 48

1 Answers1

1

See this answer as a reference.

Add an optional attribute to the entity and make it a transient property.

Then create a getter (assuming your property is called sectionGroup)

- (NSNumber *) sectionGroup
{
  [self willAccessValueForKey:@"sectionGroup"];
  NSNumber *group = [NSNumber numberWithInt:0];
  if(numValue > 15)
  {
    group = [NSNumber numberWithInt:1];
  }
  [self didAccessValueForKey:@"sectionGroup"];
  return group;
}

Now, you can use sectionGroup as your sectionNameKeyPath.

Community
  • 1
  • 1
Dima
  • 23,484
  • 6
  • 56
  • 83
  • I had to say in OP that I want another way, because change the entity for such things feels like kind of dirty. – folex Jul 12 '12 at 07:53