gpt4 book ai didi

ios - 如何在核心数据关系上划分 UITableView?

转载 作者:行者123 更新时间:2023-11-29 11:24:32 26 4
gpt4 key购买 nike

我有 2 个实体 - BlogEntry 和 BlogComments。

BlogEntry.comments 是与 BlogComments 的“一对多”关系

| BlogEntry     |
-----------------
| subject |
| body |
| comments (rel)|



| BlogComments |
------------------
| commentText |
| blogEntry (rel)|

现在,我有一个 TableView ,我希望它的第一行是 BlogEntry 正文(文本),其余行是 BlogComments。 NSFetchedResultsController 可以做到这一点吗?我能断绝这样的关系吗?如果是这样,有人可以指出我正确的方向吗?

最佳答案

使用分组的 UITableView 以及使用 sectionNameKeyPathNSPredicateNSFetchedResultsController:

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

[fetchRequest setFetchBatchSize:20];

// Ensure we get a single blog entry and all it's associated comments
NSPredicate *predicate =
[NSPredicate predicateWithFormat:@"blogEntryID=%@", blogEntryID];

[fetchRequest setPredicate:predicate];

NSString *key = @"blogEntry.subject";
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:key
ascending:YES];
NSArray *sortDescriptors = @[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];

NSFetchedResultsController *aFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:keycacheName:nil];

aFetchedResultsController.delegate = self;

要确定部分的标题,请使用 fetchedResultsController 的部分属性:

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

return [sectionInfo name];
}
return nil;
}

要确定特定部分中的行数:

- (NSInteger)tableView:(UITableView *)tableView 
numberOfRowsInSection:(NSInteger)section
{
NSInteger numberofRows = 0;

if ([[fetchedResultsController sections] count] > 0)
{
id <NSFetchedResultsSectionInfo> sectionInfo =
[[fetchedResultsController sections] objectAtIndex:section];
numberofRows = [sectionInfo numberOfObjects];
}

return numberofRows;
}

最后,获取 TableView 中的部分数:

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

结果是一个 TableView ,其中 1 个部分表示博客条目及其所有相关的博客评论作为 TableView 中的行。

关于ios - 如何在核心数据关系上划分 UITableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3289803/

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