iPhone - разбить базовые данные на разделы с помощью NSFetchResultsController - PullRequest
6 голосов
/ 05 декабря 2011

Итак, я успешно реализовал Core Data для извлечения объектов с сервера, их сохранения и отображения в UITableView. Однако сейчас я хочу разбить их на отдельные разделы. Я искал несколько дней, и NSFetchedResultsController, кажется, смущает меня, хотя способ, которым я использую это, работает. В моей сущности есть ключ под названием articleSection, который устанавливается при добавлении элемента в базовые данные с такими элементами, как «Top», «Sports», «Life». Как бы я разбил их на отдельные разделы в моем UITableView? Я читал об использовании нескольких NSFetchedResultsControllers, но я настолько разочарован, насколько это возможно.

Любые предложения или помощь будет принята с благодарностью.

1 Ответ

17 голосов
/ 05 декабря 2011

Документация для NSFetchedResultsController содержит пример кода, который отлично работает.

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

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = /* get the cell */;
    NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
    // Configure the cell with data from the managed object.
    return cell;
}

- (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];
}

Установите sortDescriptors запроса на выборку, чтобы результаты сортировались по articleSection.
Установите sectionKeyPath в "articleSection", чтобы NSFetchedResultsController создавал разделы для вас. Примерно так:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:self.managedObjectContext];;
request.fetchBatchSize = 20;
// sort by "articleSection"
NSSortDescriptor *sortDescriptorCategory = [NSSortDescriptor sortDescriptorWithKey:@"articleSection" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObjects:sortDescriptorCategory, nil];;

// create nsfrc with "articleSection" as sectionNameKeyPath
NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"articleSection" cacheName:@"MyFRCCache"];
frc.delegate = self;
NSError *error = nil;
if (![frc performFetch:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}
self.fetchedResultsController = frc;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...