Кнопка обновления iOS в View Controller Nav: перезагрузка всех tableViewCells, созданных из проанализированного JSON, при нажатии

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

Мое приложение простое: несколько строк TableViewCells заполнены данными из проанализированного канала JSON. При щелчке по ячейке информация об этой ячейке передается в SecondViewController и отображается. Канал JSON также сохраняется в .plist, и в случае, если Интернет недоступен, TableViewCells заполняются из .plist.

Все работает отлично.

Однако последнее, что мне нужно, - это кнопка обновления в верхней части моего FirstViewController, чтобы обновить канал JSON и все ячейки в таблице с новыми данными из новых переменных. Однако я столкнулся с проблемой при реализации этого:

Мой исходный вызов JSON и переменные для заполнения ячеек находятся в методе ViewDidLoad. Когда представление загружается, эти переменные «устанавливаются» и не обновляются.Кроме того, я могу переместить вызов JSON и переменные в viewWillLoad, который будет обновлять таблицу каждый раз после щелчка по ячейке и последующего нажатия кнопки «назад» к firstViewController - это успешно обновит JSON и ячейки, однако это повлияет на скорость и заставляет контроллер представления «приостанавливаться» при возврате к MainViewController, что делает вызов моего исходного JSON и установку моих переменных в viewWillLoad нежизнеспособным вариантом.

Я создал кнопку перезагрузки в ViewDidLoad, которая связана с методом обновления IBAction:

Программно создать кнопку в ViewDidLoad:

// Reload issues button
UIBarButtonItem *button = [[UIBarButtonItem alloc]
                           initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                           target:self
                           action:@selector(refresh:)];
self.navigationItem.rightBarButtonItem = button;
[button release];

Метод действия, с которым она связана:

- (IBAction)refresh:(id)sender {

    myRawJson = [[NSString alloc] initWithContentsOfURL:[NSURL  
                                  URLWithString:@"http://www.yoursite.com/json.JSON"]  
                                  encoding:NSUTF8StringEncoding 
                                  error:nil];

    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSDictionary * myParsedJson = [parser objectWithString:myRawJson error:NULL];

// New updated dictionary built from refreshed JSON
    allLetterContents = [myParsedJson objectForKey:@"nodes"];

// Log the new refreshed JSON
    NSLog(@"You clicked refresh. Your new JSON is %@", myRawJson);

    //Maybe use the notification center?? But don't know how to implement.
    //[[NSNotificationCenter defaultCenter] addObserver:self 
                                            selector:@selector(refreshView:) 
                                            name:@"refreshView" object:nil];
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshView" 
                                            object:nil];

    }

    [self.tableView reloadRowsAtIndexPaths:[self.tableView indexPathsForVisibleRows] 
                     withRowAnimation:UITableViewRowAnimationNone];

    [myRawJson release];
}

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

У меня вопрос: как я могу заставить tableViewCells «обновиться» с помощью этих новых данных? Могу ли я просто заставить кнопку перезагрузить весь контроллер представления, чтобы он снова вызвал ViewDidLoad? Нужно ли мне переосмыслить структуру своих приложений или переместить исходные переменные из viewDidLoad?

Я читал несколько сообщений в NSNotificationCenter, но реализация этого все еще сбивает меня с толку, поскольку я новичок в iOS-разработка.

Спасибо ~


Обновление:


Он все еще не обновляется. Вот мой полный код кнопки обновления с [self.tableView reloadData]; позвонил в конце моего IBAction.

    - (IBAction)refresh:(id)sender {
        [DSBezelActivityView newActivityViewForView:        
                         self.navigationController.navigationBar.superview     
                         withLabel:@"Loading Feed..." width:160];

        myRawJson = [[NSString alloc] initWithContentsOfURL:[NSURL 
                     URLWithString:@"http://site.com/mobile.JSON"] 
                     encoding:NSUTF8StringEncoding 
                     error:nil];

        SBJsonParser *parser = [[SBJsonParser alloc] init];
        NSDictionary * myParsedJson = [parser objectWithString:myRawJson error:NULL];
        allLetterContents = [myParsedJson objectForKey:@"nodes"];

        BOOL isEmpty = ([myParsedJson count] == 0);

        if (isEmpty) {
            NSString *refreshErrorMessage = [NSString 
stringWithFormat:@"An internet or network connection is required."];
            UIAlertView *alert = [[UIAlertView alloc] 
                                 initWithTitle:@"Alert" 
                                 message: refreshErrorMessage 
                                 delegate:self 
                                 cancelButtonTitle:@"Close" 
                                 otherButtonTitles:nil];
            [alert show];
            [alert release];

            allLetterContents = [NSMutableDictionary 
                                dictionaryWithContentsOfFile:[self saveFilePath]];
            //NSLog(@"allLetterContents from file: %@", allLetterContents);

        } else {

        NSLog(@"Your new allLetterContents is %@",  allLetterContents);

          // Fast enumeration through the allLetterContents NSMutableDictionary
          for (NSMutableDictionary * key in allLetterContents) {
            NSDictionary *node = [key objectForKey:@"node"];
            NSMutableString *contentTitle = [node objectForKey:@"title"];        
            NSMutableString *contentNid = [node objectForKey:@"nid"];
            NSMutableString *contentBody = [node objectForKey:@"body"];
            // Add each Title and Nid to specific arrays
            //[self.contentTitleArray addObject:contentTitle];
            [self.contentTitleArray addObject:[[contentTitle 
                                     stringByReplacingOccurrencesOfString:@"&" 
                                     withString:@"&"] mutableCopy]];
            [self.contentNidArray addObject:contentNid];
            [self.contentBodyArray addObject:contentBody];
          }

        }

        [self.tableView reloadData];

        [DSBezelActivityView removeViewAnimated:YES];
        [myRawJson release];
    }

Я настраиваю ячейку в cellForRowAtIndexPath ( Обновлено: опубликован весь метод ):

- (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];
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
            cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
        }
    }

    // Configure the cell.
    cell.textLabel.text = [self.contentTitleArray objectAtIndex: [indexPath row]];
    cell.detailTextLabel.text = [self.contentNidArray objectAtIndex: [indexPath row]];
    return cell;
}

Установка на didSelectRowAtIndexPath:

self.detailViewController.currentNodeTitle = [contentTitleArray 
                                             objectAtIndex:indexPath.row];
self.detailViewController.currentNodeNid= [contentNidArray 
                                          objectAtIndex:indexPath.row];
self.detailViewController.currentNodeBody = [contentBodyArray 
                                            objectAtIndex:indexPath.row];

Поэтому при нажатии моей кнопки обновления таблица должна * обновиться с новым json, но не ... Я пропустил шаг?

enter image description here

Кроме того, это может быть не важно, но я меняю цвета для каждой второй строки с помощью:

// Customize the appearance of table view cells.
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row % 2)
    {
        [cell setBackgroundColor:[UIColor colorWithRed:221.0/255.0 green:238.0/255.0 blue:255.0/255.0 alpha:1]];
        cell.textLabel.textColor = [UIColor colorWithRed:2.0/255.0 green:41.0/255.0 blue:117.0/255.0 alpha:1];
        cell.detailTextLabel.textColor = [UIColor colorWithRed:2.0/255.0 green:41.0/255.0 blue:117.0/255.0 alpha:1];

    }    else [cell setBackgroundColor:[UIColor clearColor]];
}

Update

enter image description here

6
задан Pat 24 December 2011 в 16:55
поделиться