Используйте сгруппированные UITableView
вместе с NSFetchedResultsController
, который использует sectionNameKeyPath
и NSPredicate
:
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;
}
И, наконец, чтобы получить количество разделов в табличном представлении:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSUInteger count = [[fetchedResultsController sections] count];
return count;
}
В результате получается табличное представление с 1 разделом, представляющим запись блога и все связанные с ней комментарии блога в виде строк в tableView.