iPhone - 使用NSFetchedResultsController将Core Data分解为多个部分

时间:2011-12-05 07:22:09

标签: iphone uitableview core-data nsfetchedresultscontroller

所以我成功实现了Core Data从服务器检索对象,保存它们,并在UITableView中显示它们。但是现在,我希望将它们分成几个部分。我已经看了几天了,NSFetchedResultsController似乎让我很困惑,即使我使用它的方式有效。我的实体中有一个名为“articleSection”的密钥,当项目添加到Core Data时,设置了诸如“Top”“Sports”“Life”之类的项目。我如何在UITableView中将它们分成不同的部分?我已经阅读了有关使用多个NSFetchedResultsControllers的内容,但我对此感到非常沮丧。

任何建议或帮助将不胜感激。

1 个答案:

答案 0 :(得分:17)

documentation for NSFetchedResultsController包含完美运行的示例代码。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[self.fetchedResultsController sections] count];
}

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = /* get the cell */;
    NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
    // Configure the cell with data from the managed object.
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo name];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [self.fetchedResultsController sectionIndexTitles];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return [self.fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}

设置获取请求的sortDescriptors,以便按articleSection对结果进行排序 将sectionKeyPath设置为“articleSection”,以便NSFetchedResultsController为您创建节。像这样:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:self.managedObjectContext];;
request.fetchBatchSize = 20;
// sort by "articleSection"
NSSortDescriptor *sortDescriptorCategory = [NSSortDescriptor sortDescriptorWithKey:@"articleSection" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObjects:sortDescriptorCategory, nil];;

// create nsfrc with "articleSection" as sectionNameKeyPath
NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"articleSection" cacheName:@"MyFRCCache"];
frc.delegate = self;
NSError *error = nil;
if (![frc performFetch:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}
self.fetchedResultsController = frc;