使用NSFetchedResultsController时,一组节不一致

时间:2009-10-17 22:47:32

标签: iphone core-data

我正在使用NSFetchedResultsController,其fetchRequest具有谓词。但是,每次执行时,查询似乎都不会给我一致的分组。

我为NSFetchedResultsController设置了'sectionNameKeyPath',根据我是否在运行fetch之前一直使用root对象,我得到了不同数量的部分。有时我会得到3个部分和其他时间,它会返回1个部分,即预期结果。

我如何创建FetchRequestController:

// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

// Configure the request's entity and its predicate.        
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employee"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];

// The predicate to find all employees associated with a Group
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.groups IN %@",
                         [division groups]];

[fetchRequest setPredicate:predicate];

// Sort based on create date and time
NSSortDescriptor *createDateSortDcptor = [[NSSortDescriptor alloc] initWithKey:@"createDateTime" ascending:YES];

NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:createDateSortDcptor, nil];

[fetchRequest setSortDescriptors:sortDescriptors];

// should be grouped by the 'Group' employee belongs to.
NSFetchedResultsController *controller = 
  [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
      managedObjectContext:context 
      sectionNameKeyPath:@"groups" 
      cacheName:@"Root"];                   

我的对象模型与其他问题中概述的相同:

https://stackoverflow.com/questions/1580236/how-to-setup-a-predicate-for-this-query 有没有办法确保每次都能获得一致的分组?

1 个答案:

答案 0 :(得分:1)

事实证明这很简单:

NSFetchedResultsController *controller = 
  [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
      managedObjectContext:context 
      sectionNameKeyPath:@"groups.name" 
      cacheName:@"Root"];

我没有意识到我可以在'sectionNameKeyPath'

中附加二级属性名称