NSFetchedResultsController:获取节对象

时间:2013-12-28 11:25:21

标签: ios core-data nsfetchedresultscontroller

我已经使用NSFetchedResultsController将我的子类别分组到各自的主要类别中并实现了自定义标题:

我的获取:

    NSError *error = nil;
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SubCategory"];

    NSSortDescriptor *mainCatPosition = [[NSSortDescriptor alloc]
                            initWithKey:@"belongsToMainCategory.position" ascending:YES];
    NSSortDescriptor *subCatPosition = [[NSSortDescriptor alloc]
                            initWithKey:@"position" ascending:YES];

    request.sortDescriptors = [NSArray arrayWithObjects:mainCatPosition,subCatPosition,nil];
    request.predicate = [NSPredicate predicateWithFormat:@"display = %@", [NSNumber numberWithBool:YES]];
    [self.db.managedObjectContext executeFetchRequest:request error:&error];

    self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request
                                                                       managedObjectContext:self.budgetDatabase.managedObjectContext
                                                                         sectionNameKeyPath:@"belongsToMainCategory.position"
                                                                                  cacheName:nil];

我的自定义标题:

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    SectionHeader *header=[[[NSBundle mainBundle] loadNibNamed:@"SectionHeader" owner:self options:nil] objectAtIndex:0];

    MainCategory *mainCategory = [[self.fetchedResultsController sections] objectAtIndex:section];

    //Icon
    UIImage *icon;
    if(!mainCategory.icon){
        icon = [UIImage imageNamed:@"DefaultIcon.png"];
    } else {
        icon = [UIImage imageNamed:mainCategory.icon];
    }
    header.categoryIcon.image = icon;
    header.sectionBackgroundImage.image = [[UIImage imageNamed:@"content-bkg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];

    return header;
}

但我猜这个:MainCategory * mainCategory = [[self.fetchedResultsController sections] objectAtIndex:section]; 是错的?如何使用其所有属性访问此mainCategory对象?

1 个答案:

答案 0 :(得分:2)

NSFetchedResultsController的sections数组包含一些确认为NSFetchedResultsSectionInfo协议的类的对象。 sections数组中没有NSManagedObjects 如果你认为它是有意义的,因为你的获取并不总是沿着其他对象划分,更常见的是,获取由NSDates,NSStrings,NSNumbers或其他任何部分划分。

您可能会从该部分获取SubCategory个对象,然后从此子类别中获取MainCategory。像这样:

id <NSFetchedResultsSectionInfo> sectionInfo = self.fetchedResultsController.sections[section];

if ([sectionInfo numberOfObjects] > 0) {
    SubCategory *subCategory = [sectionInfo objects][0];
    MainCategory *mainCategory = subCategory.belongsToMainCategory;

    ....
}
else {
    // empty section... whatever
}