Objective c 视图控制器导航中的iOS刷新按钮:单击时重新加载从解析的JSON创建的所有TableViewCell

Objective c 视图控制器导航中的iOS刷新按钮:单击时重新加载从解析的JSON创建的所有TableViewCell,objective-c,ios,uitableview,uiviewcontroller,nsnotifications,Objective C,Ios,Uitableview,Uiviewcontroller,Nsnotifications,我有一个相当重要的概念问题,很多人都问过这个问题,但是没有一个现成的清晰答案可以通过搜索找到 我的应用程序很简单:几行TableViewCells中填充了来自解析JSON提要的数据。单击单元格时,该单元格的信息将传递给SecondViewController并显示。JSON提要还存储在.plist中,如果internet不可用,则从.plist填充TableViewCell 这一切都很好 但是,我最不需要的是在FirstViewController顶部的一个刷新按钮来刷新JSON提要,并使用来自

我有一个相当重要的概念问题,很多人都问过这个问题,但是没有一个现成的清晰答案可以通过搜索找到

我的应用程序很简单:几行TableViewCells中填充了来自解析JSON提要的数据。单击单元格时,该单元格的信息将传递给SecondViewController并显示。JSON提要还存储在.plist中,如果internet不可用,则从.plist填充TableViewCell

这一切都很好

但是,我最不需要的是在FirstViewController顶部的一个刷新按钮来刷新JSON提要,并使用来自新变量的新数据刷新表中的所有单元格。但是,我在实现这一点时遇到了一个问题:

我最初的JSON调用和填充单元格的变量位于ViewDidLoad方法中。当视图加载时,这些变量被“设置”并且不刷新。此外,我可以将JSON调用和变量移动到viewWillLoad中—每次单击单元格,然后单击“返回”到firstViewController后,都会刷新表—这将成功更新JSON和单元格,但它会影响速度并使视图控制器“暂停”返回MainViewController时,调用我的原始JSON并在ViewLoad中设置变量将成为一个不可行的选项

我在ViewDidLoad中创建了一个重载按钮,该按钮链接到iAction方法“刷新”:

在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];
}
它链接到的操作方法:

// 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开发还相当陌生

谢谢~


更新:

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

它仍然没有更新。这是我的完整刷新按钮代码,带有[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];
    }
我正在CellForRowatineXpath配置单元格(更新:发布整个方法):

在didSelectRowAtIndexPath上设置它:

self.detailViewController.currentNodeTitle = [contentTitleArray 
                                             objectAtIndex:indexPath.row];
self.detailViewController.currentNodeNid= [contentNidArray 
                                          objectAtIndex:indexPath.row];
self.detailViewController.currentNodeBody = [contentBodyArray 
                                            objectAtIndex:indexPath.row];
因此,当单击“我的刷新”按钮时,表应该*用新的json刷新,但不会。。我漏了一步吗

此外,这可能并不重要,但我正在使用以下方法更改每一行的颜色:

// 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]];
}
更新


您需要调用重新加载方法

[self.tableView reloadData];
这将触发
dataSource
delegate
事件,并刷新
UITableView

您可以在以下位置找到更多信息:

调用此方法以重新加载用于构造表的所有数据,包括单元格、节页眉和页脚、索引数组等。为了提高效率,表视图只重新显示那些可见的行


这是许多其他帖子所说的,但当我添加[self.tableView reloadData]时;到-(iAction)refresh:(id)sender结束时,它没有任何效果。还有其他想法吗?或者我只是在错误的地方调用它?我已经更新了我的帖子,包括我的IBAction代码和一些更多信息。也许我遗漏了一些代码?我可以通过运行应用程序,然后更新JSON源来验证JSON是否已更改,当我单击“刷新”按钮时,我的NSLog显示刷新按钮输出新内容,但是单元格不更新。我怀疑
cellForRowAtIndexPath:
有问题,您只粘贴了一小部分。@Krizz-我添加了整个cellForRowAtIndexPath。我没有发布整个方法,因为除了我添加的内容外,它是完全标准的。-感谢您使用调试器验证了
[self.tableView reloadData]正在访问,并且
tableView
不是空的?我的视图中当前有包含内容的单元格,因此我认为这意味着tableView有单元格,因此不是空的。下面的日志记录了大于0的NSLog:if(self.tableView>0){[self.tableView reloadData];NSLog(@“您的tableView大于0”);}——是的,我认为它不是零。我注意到的另一件事是,即使我的iAction用代码连接到refresh方法,该方法旁边的圆圈仍然显示为未链接。这必须是在使用代码而不是GUI创建按钮时造成的。(附截图)。