NSFetchedResultsController没有组合相似的部分

时间:2014-04-10 02:24:51

标签: ios core-data nsfetchedresultscontroller

我正在尝试使用NSFetchedResultsController在表视图中显示数据。我的数据模型有一组用户,每个用户都有一个类别数组,每个类别都有一组组织,每个组织都有一组帐户。表视图显示来自单个用户的数据。每行代表属于用户的组织,组织分为几个部分,每个部分包含属于特定类别的组织。在我的app委托中,我使用一些虚拟数据填充我的应用程序,NSFetchedResultsController显示该数据正常。问题是,当我尝试将新组织添加到现有类别时,会添加该行,但会将其添加到仅包含该行的新部分,而不是与包含该类别的其他组织的部分合并。

以下是我的NSFetchedResults控制器的代码:

- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"PKOrganization" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];

// Tell the fetch request to only retrieve the organizations from the proper user
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(category.user.name = '%@')", self.user.name]]];

// Sort the data
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"category.name" ascending:YES];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = @[sortDescriptor1,sortDescriptor2];
[fetchRequest setSortDescriptors:sortDescriptors];

// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"category" cacheName:@"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;

NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
    // Replace this implementation with code to handle the error appropriately.
    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return _fetchedResultsController;
}

值得注意的是,我能够告诉数据是按预期添加的。它只是没有正确显示。

1 个答案:

答案 0 :(得分:1)

尝试更改此行

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

对此:

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"category.name" cacheName:@"Master"];

根据我的经验,我需要sectionNameKeyPath与第一个sortDescriptor完全相同才能使部分正常工作。