LoginSignup
3
3

More than 5 years have passed since last update.

NSFetchedResultControllerでのセクションごとのソート順がUITableViewControllerで反映されない場合の対処法

Last updated at Posted at 2014-04-08

参考
http://yoo-s.com/topic/detail/178

NSFetchedResultControllerを使ったセクションごとのソートがうまく行かないのはsetSortDescriptorsとsectionNameKeyPathの不一致やSortDescriptor配列の順序が原因でした。(多分。これを直したらうまく行ったけど、ちょっと釈然としない)

修正前

NSSortDescriptor* sortDescriptorWithName = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                 ascending:YES];


  NSArray* aSortDescriptor = @[sortDescriptorWithName];
  [fetchRequest setSortDescriptors:aSortDescriptor];
  NSPredicate* predicate = [NSPredicate predicateWithFormat:@"status >= 0"];
  [fetchRequest setPredicate:predicate];

  NSFetchedResultsController* fetchedResultsController =
  [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                      managedObjectContext:self.managedObjectContext
                                        sectionNameKeyPath:@"status"
                                                 cacheName:@"Master"];

修正後

NSSortDescriptor* sortDescriptorWithName = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                 ascending:YES];

  NSSortDescriptor* sortDescriptorWithStatus = [[NSSortDescriptor alloc] initWithKey:@"status"
                                                                 ascending:YES];

  NSArray* aSortDescriptor = @[sortDescriptorWithStatus,sortDescriptorWithName];
  [fetchRequest setSortDescriptors:aSortDescriptor];
  NSPredicate* predicate = [NSPredicate predicateWithFormat:@"status >= 0"];
  [fetchRequest setPredicate:predicate];

  NSFetchedResultsController* fetchedResultsController =
  [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                      managedObjectContext:self.managedObjectContext
                                        sectionNameKeyPath:@"status"
                                                 cacheName:@"Master"];

ちゃんとsectionNameKeyPathで指定したアトリビュート名のNSSortDescriptorを作成して、パラメータにセットしてあげる必要があります。

ところで、最初に下記のような修正をした結果、うまくソートされませんでした。

NSArray* aSortDescriptor = @[sortDescriptorWithName, sortDescriptorWithStatus];

sectionNameKeyPathにマッチするNSSortDescriptorは配列の先頭にセットする必要がありそうです。
先頭から順番にsortdescriptorが適用されることを考えると妥当かなと思うのですが、
こちらの仕様未確認なので私の開発環境下での実験結果として記述しておきます。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3