2013-06-12 9 views
5

結果から2つのセクションを持つテーブルビューが得られるフェッチ要求があります。コアデータNSFetchRequest with grouping

マイモデル:

@interface Player : NSManagedObject 

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

このモデルのフェッチ要求が第二項にNO == 1つのセクション、およびisFacebookFriendでYES == isFacebookFriendている人々のセクションになるはずです。

私は

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

セクションとテーブルビューを作成するには、NSFetchedResultsControllersectionNameKeyPathパラメータ を使用する必要があります。また、セクション名のキーパスに従って をソートする(最初の)ソート記述子を追加する必要があります。

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を設定することはお勧めしません。

関連する問題