Reputation: 10432
I have a fetch request that shoul result in a tableview with two sections from the result.
My model:
@interface Player : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * isFacebookFriend;
The fetch request on this model should result in a section with people that are isFacebookFriend == YES in one section, and isFacebookFriend == NO in the second section.
I tried with
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
HBAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Player" inManagedObjectContext:appDelegate.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
[fetchRequest setSortDescriptors:@[nameDescriptor]];
[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setPropertiesToGroupBy:@[@"isFacebookFriend"]];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:appDelegate.managedObjectContext sectionNameKeyPath:nil cacheName:@"playerCache"];
NSError *error;
[_fetchedResultsController performFetch:&error];
But that did not do it. Error was:
2013-06-12 12:27:28.364 TwentyQuestions[25015:c07] Unbalanced calls to begin/end appearance transitions for <UINavigationController: 0xb676aa0>.
2013-06-12 12:27:31.119 TwentyQuestions[25015:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'SELECT clauses in queries with GROUP BY components can only contain properties named in the GROUP BY or aggregate functions ((<NSAttributeDescription: 0xc382320>), name hasRegisteredForGame, isOptional 1, isTransient 0, entity Player, renamingIdentifier hasRegisteredForGame, validation predicates (
), warnings (
), versionHashModifier (null)
userInfo {
}, attributeType 800 , attributeValueClassName NSNumber, defaultValue (null) is not in the GROUP BY)'
Upvotes: 5
Views: 4725
Reputation: 539775
To create a table view with sections, you have to use the sectionNameKeyPath
parameter
of NSFetchedResultsController
. You also have to add a (first) sort descriptor that sorts
according to the section name key path.
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
NSSortDescriptor *isFacebookFriendDescriptor = [[NSSortDescriptor alloc] initWithKey:@"isFacebookFriend" ascending:NO];
[fetchRequest setSortDescriptors:@[isFacebookFriendDescriptor, nameDescriptor]];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:appDelegate.managedObjectContext
sectionNameKeyPath:@"isFacebookFriend"
cacheName:@"playerCache"];
You don't have to set setPropertiesToGroupBy
, and I would not recommend to set
NSDictionaryResultType
because that disables the automatic update notifications.
Upvotes: 9