Дублируйте строки под заголовками разделов с помощью NSFetchedResultsController
Я так близко... но, должно быть, чего-то не хватает.
В моей местной базе данных есть список полей для гольфа с различными деталями, включая, среди прочего, штат, первую букву названия штата (A, C, D,) и т. Д. NSFetchedResultsController
захватывает список курсов и (или работал) отлично показывает все штаты, для которых есть курс, для которого у меня есть записи.
В любом случае... кажется, что главы секций работают... но мои штаты теперь дублируются на количество курсов, которые есть в каждом штате.
Код и снимок экрана ниже. Что мне не хватает?!? Это должно быть что-то настолько очевидное.
-(NSFetchedResultsController *)fetchedResultsController {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Courses"
inManagedObjectContext:_managedObjectContext];
request.entity = entity;
request.sortDescriptors = [NSArray arrayWithObject:
[NSSortDescriptor
sortDescriptorWithKey:@"locState"
ascending:YES
selector:@selector(caseInsensitiveCompare:)]];
request.returnsDistinctResults = YES;
request.fetchBatchSize = 20;
NSFetchedResultsController *frc = [[NSFetchedResultsController alloc]
initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:@"locStateSectionHead"
cacheName:nil];
frc.delegate = self;
NSError *error = nil;
if (![frc performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
self.fetchedResultsController = frc;
return _fetchedResultsController;
}
А затем остальные настройки tableView:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
if ([[_fetchedResultsController sections] count] > 0) {
id <NSFetchedResultsSectionInfo> sectionInfo = [[_fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
} else {
return 0;
}
}
- (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];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"stateCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
// Configure the cell...
Courses *course_info = [_fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = course_info.locState;
return cell;
}
1 ответ
Если вы хотите, чтобы в табличном представлении отображались состояния, то ваш NSFetchedResultsController
должен получить государство, а не курс. Вы получаете дублирование, потому что вы сортируете по курсам, и у вас есть несколько курсов в одном штате.
Настройте свой NSFetchedResultsController
чтобы загрузить объект State, тогда ваше табличное представление будет отображаться правильно. Оттуда, когда пользователь выбирает состояние, вы можете использовать отношение от состояния к курсу, чтобы отобразить вашу следующую сцену.
Вы просто имеете это задом наперед:)