Базовые данные в секционном TableView упорядочены неправильно - PullRequest
1 голос
/ 05 сентября 2011

я создаю табличное представление, используя данные ядра и NSFetchedResultsController с sectionNameKeyPath.Мои сущности Core-Data выглядят хорошо, также в базе данных SQL данные выглядят хорошо.

Сущность называется «Cast» и выглядит следующим образом:

Cast
  -> job
  -> department // the attribute i want the sections from

я генерирую свой NSFetchedResultsController вот так

// fetch controller
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Cast" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSSortDescriptor *sort1 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] initWithKey:@"job" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sort1, sort2, nil]];
[sort1 release];
[sort2 release];

// Predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"movie == %@", self.movie];
[fetchRequest setPredicate:predicate];

// Generate it
NSFetchedResultsController *theFetchedResultsController = 
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
                                            managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"department" 
                                                       cacheName:nil];
self.fetchedResultsController = theFetchedResultsController;
self.fetchedResultsController.delegate = self;

[fetchRequest release];
[theFetchedResultsController release];

// Fetch Casts
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
    // Update to handle the error appropriately.
    XLog("Unresolved error %@, %@", error, [error userInfo]);
}

Но результат следующий (я добавил атрибут "отдел" в атрибут детализации, чтобы показать проблему)

enter image description here

как вы видете.разделы генерируются правильно, но затем отдельные разделы полностью случайным образом вставляются в разделы.

кто-нибудь может увидеть ошибку в моем коде?

вот остальная часть кода, который связанв ячейку / раздел материала

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


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

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    Cast *currentCast = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = currentCast.name;
    //cell.detailTextLabel.text = currentCast.job;

    // just temporary
    cell.detailTextLabel.text = currentCast.department;

    return cell;
}

- (NSString *)tableView:(UITableView *)tableView  titleForHeaderInSection:(NSInteger)section {

    NSString *jobTitle = [[[fetchedResultsController sections] objectAtIndex:section] name];
    return jobTitle;

}

спасибо за все подсказки.пожалуйста, оставьте комментарий, если что-то неясно.

1 Ответ

5 голосов
/ 05 сентября 2011

Вы должны сначала отсортировать по department.

NSSortDescriptor *sort1 = [[NSSortDescriptor alloc] initWithKey:@"department" ascending:YES];
NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] initWithKey:@"job" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sort1, sort2, sort3, nil]];
[sort1 release];
[sort2 release];
[sort3 release];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...