我遇到了一个问题,我不知道它来自哪里,与 CoreData 相关。在我的数据库中,有一组类别(带有名称和描述),其中包含元素(使用一对多关系)。
我想在给定Category
类属性的情况下将我的表格视图划分为部分,但是当我尝试使用它时sectionNameKeyPath:
,结果NSFetchedResultsController
有 0 个部分。如果我将 nil 传递给此参数,则它有 1 个部分。
代码如下:
- (NSFetchedResultsController*) fetchedResultsController
{
if(fetchedResultsController)
return fetchedResultsController;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Category"
inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:10];
// Edit the sort key as appropriate.
NSSortDescriptor *checkDescriptor = [[NSSortDescriptor alloc] initWithKey:@"checked"
ascending:YES];
NSSortDescriptor *indexDescriptor = [[NSSortDescriptor alloc] initWithKey:@"orderIndex"
ascending:YES];
NSArray *sortDescriptors = @[checkDescriptor, indexDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:@"checked"
cacheName:nil];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
return nil;
} else {
fetchedResultsController.delegate = self;
return fetchedResultsController;
}
}