2013-06-12 48 views
5

我有一個提取請求,從結果中的兩個部分產生tableview。核心數據NSFetchRequest與分組

我的模型:

@interface Player : NSManagedObject 

@property (nonatomic, retain) NSString * name; 
@property (nonatomic, retain) NSNumber * isFacebookFriend; 

的獲取這種模式要求應導致與人是isFacebookFriend節==是在一個部分,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

也許顯示您的完整獲取請求代碼? –

+0

已添加。只需從核心數據中獲取標準 – hakonbogen

回答

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因爲禁用自動更新通知。