我有一个获取请求,该请求可以产生一个包含结果中两个部分的tableview。
我的模特:
@interface Player : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * isFacebookFriend;
此模型上的获取请求应该会生成一个部分,其中一个部分中的isFacebookFriend == YES,而第二部分中的isFacebookFriend == NO。
我试过
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];
但那没有做到。错误是:
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)'
答案 0 :(得分:9)
要创建包含节的表视图,您必须使用sectionNameKeyPath
参数
NSFetchedResultsController
。您还必须添加一个(第一个)排序描述符
根据部分名称键路径。
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"];
您不必设置setPropertiesToGroupBy
,我也不建议您设置
NSDictionaryResultType
因为这会禁用自动更新通知。