UITableView reloadData не перезагружается - PullRequest
3 голосов
/ 29 декабря 2011

Я совершенно озадачен, почему reloadData не перезагружает таблицу. Не звонит numberOfRowsInSection ...

fetchedResultsController получает новую строку после сохранения новых данных в core-data

Перед добавлением новых данных в табличное представление

2011-12-29 19:09:08:213 CaveConditions[56423:71939] FRC 170

После viewWillAppear и добавления данных

2011-12-29 19:09:35:908 CaveConditions[56423:71939] FRC NEW 171

TableView (aTableView) не равен нулю перед вызовом reloadData

2011-12-29 19:18:27:334 CaveConditions[56525:71939] TableVIew: <UITableView: 0x9c12000; frame = (0 0; 320 367); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x751cbb0>; contentOffset: {0, 0}>

Как только я перезапускаю приложение, оно показывает новый контент ... Я использую раскадровку и установил все соединения между таблицей и делегатом / источником данных и проверил его несколько раз. Класс является UIViewController.

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.fetchedResultsController = nil;

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

id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:0];
NSLog(@"FRC NEW %d",[sectionInfo numberOfObjects]);

[self.aTableView reloadData];
}

Не уверен, в чем тут проблема ... Есть идеи?

Edit:

Я ленивый FRC

- (NSFetchedResultsController *)fetchedResultsController 
{
if (!fetchedResultsController)
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    if (isNormalCell)
    {
        fetchRequest.entity = [NSEntityDescription entityForName:@"Condition" inManagedObjectContext:self.context];
        fetchRequest.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"diveDate" ascending:NO]];        
        fetchRequest.predicate = [NSPredicate predicateWithFormat:@"cave = %@", cave];
    } else
    {
        fetchRequest.entity = [NSEntityDescription entityForName:@"Condition" inManagedObjectContext:self.context];
        fetchRequest.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"insertDate" ascending:NO]];
        fetchRequest.returnsDistinctResults = YES;
    }
    fetchRequest.fetchBatchSize = 20;


    fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
                                                                   managedObjectContext:context 
                                                                     sectionNameKeyPath:nil 
                                                                              cacheName:nil];

    fetchedResultsController.delegate = self;
}

return fetchedResultsController;
}

Вот код

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
static NSString *CellIdentifier;

if (!isNormalCell)
    CellIdentifier = @"conditionCellReport";
else
    CellIdentifier = @"conditionCell";

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

// Set up the cell...
[self configureCell:cell atIndexPath:indexPath];

return cell;
}


- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath 
{
    Condition *condition = [fetchedResultsController objectAtIndexPath:indexPath];

    ConditionCell *conCell = (ConditionCell *)cell; 

    // Reset cell tag which normally contains the ConditionID
    conCell.tag = 0;
    conCell.img.image = nil;

    conCell.lineLabel.text = [condition.line valueForKey:@"line"];
    conCell.flowProgress.progress = [[condition.flow valueForKey:@"flowValue"] floatValue];
    conCell.percolationProgress.progress = [[condition.percolation valueForKey:@"percolationValue"] floatValue];
    conCell.sedimentProgress.progress = [[condition.sediment valueForKey:@"sedimentValue"] floatValue];
    conCell.visProgress.progress = [[condition.visibility valueForKey:@"visValue"] floatValue] / 25;
    conCell.tag = [condition.ccId intValue];
...

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

enter image description here

Ответы [ 4 ]

5 голосов
/ 30 декабря 2011

OK! Я нашел проблему. Вместо reloadData я использовал beginUpdates и endUpdates. Большое спасибо за вашу помощь! Я получил информацию от NSFetchedResultsControllerDelegate Reference

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView beginUpdates];
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView endUpdates];
}
1 голос
/ 29 декабря 2011

Если в таблице показаны правильные данные при перезапуске приложения, то методы tableView dataSource и делегат верны. Вы упоминаете, что проблема возникает после добавления новых данных (т. Е. Сохранить managedObjectContext). Если это так, то проблема в том, что вы обрабатываете NSFetchedResultsController методы делегата.

Попробуйте добавить следующее:

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.aTableView reloadData];
}

Если это решит проблему, вы можете анимировать изменения таблицы против перезагрузки всей таблицы. Документы NSFetchedResultsController имеют наглядный пример того, как это сделать.

1 голос
/ 29 декабря 2011

по-моему, вы пытаетесь выполнить выборку, когда контроллер равен нулю. я бы попробовал это так:

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.fetchedResultsController = nil;

id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:0];
NSLog(@"FRC NEW %d",[sectionInfo numberOfObjects]);

NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
[self.aTableView reloadData];
0 голосов
/ 30 декабря 2011

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

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

Для пояснения, FRC с 171 объектом должен передать эту информацию в массив, который будет использоваться для перезагрузки UITableView.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...