gpt4 book ai didi

ios - NSFetchedResultsController:获取节对象

转载 作者:行者123 更新时间:2023-11-28 22:19:19 26 4
gpt4 key购买 nike

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

我的获取:

    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 对象及其所有属性?

最佳答案

sections NSFetchedResultsController 的数组包含某个类的对象,这些对象确认 NSFetchedResultsSectionInfo协议(protocol)。 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
}

关于ios - NSFetchedResultsController:获取节对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20813979/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com