IOS update button in View Nav Nav: reloads all ViewCells created from JSON parsing when clicked

I have a pretty important conceptual issue that many people have asked about, but there is no search query that can be found when searching.

My application is simple: a few rows of TableViewCells filled with data from the processed JSON channel. When a cell is clicked, the cell information is passed to the SecondViewController and displayed. The JSON channel is also saved in the .plist, and if the Internet is unavailable, TableViewCells are populated from the .plist.

This all works great.

However, the last thing I need is an update button at the top of my FirstViewController to update the JSON channel and all the cells in the table with the new data from the new variables. However, I ran into a problem with this:

My original JSON call, and the variables to populate the cells are in the ViewDidLoad method. When the view is loaded, these variables are “set” and are not updated. In addition, I can move the JSON call and variables to viewWillLoad - which will update the table each time I click on the cell, and then click back on the firstViewController - this will successfully update the JSON and cells, however it affects the speed and allows the view controller " pause "upon returning to the MainViewController, which causes my original JSON to be called and set my variables to viewWillLoad for an unstable option.

I created a reload button in ViewDidLoad, which is associated with the IBAction "refresh" method:

Create Button Programitically in ViewDidLoad:

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

Method of action associated with:

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

In the above code, you can see that I call back JSON every time a button is clicked and a message is written to the console with a new JSON. It works. I even rebuilt a dictionary that successfully adds new content.

My question is: how can I get tableViewCells to "update" this new data? Can I just get the button to reload the entire view controller - so that it calls ViewDidLoad again? Should I rethink the structure of my applications or transfer source variables from viewDidLoad?

I read some posts at NSNotificationCenter, but the implementation of this still puzzles me, as I'm pretty new to iOS development.

Thanks ~


Update:


It is still not updated. Here is my full refresh button code with [self.tableView reloadData]; at the end of my 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]; } 

I am setting the cell to cellForRowAtIndexPath ( Updated: Added the whole method ):

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

Setting it to didSelectRowAtIndexPath:

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

So, when you click the refresh button, the table should * update with the new json, but not .. Am I missing a step?

enter image description here

Also, this may not be important, but I change the colors for each other line with:

 // 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
source share
1 answer

You need to call the reboot method.

 [self.tableView reloadData]; 

This will trigger the dataSource and delegate events and update the UITableView .

For more information, see the UITableView Class Reference :

Call this method to reload all the data used to build the table, including cells, section headers and footers, index arrays, etc. For efficiency, only rows that are visible are displayed in the table view.

+5
source

Source: https://habr.com/ru/post/904336/


All Articles