mensch
mensch

Reputation: 4411

Refreshing XML data and updating a UITableView

I'm developing an iPhone application which uses a TableView to display XML data. The XML data comes from an external resource and is parsed and put into an object for use as a table dataSource. The application uses a UITabBar and multiple ViewControllers all programmatically created and using the same dataSource.

Everything is fine and dandy, but I'd like to implement a refresh button, so that a user can refresh the content (globally, so all the ViewControllers should be updated). The parser will query the XML again and create a new object. The problem I'm having is that I can't seem to repopulate the tableview with my new data. I get the updated data object. Actually updating the tableview is a problem though. I've tried to set setDataSource and call reloadData, but this results in a crash due to an unrecognised selector.

The XML stuff is called from my AppDelegate and all the parsing logic is in Parser.m. The refresh function is called in RootViewController.m, which implements the UITableViewDataSource protocol:

- (void)refreshXMLFeed:(id)sender {
  NSArray *tableControllersData = [appDelegate getData];
  [self.tableView setDataSource: tableControllersData];
  [self.tableView reloadData];  
}

How would I approach this issue? Should get the new data and reload the table view in the RootViewController as I have been trying to accomplish. Or should the data parsing be triggered in the AppDelegate and only the reloading of the TableView in RootViewController.

If necessary I can update my question with the necessary code, I'm not sure which parts are relevant at this point.

RootViewController.h:

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController {
  MyAppDelegate *appDelegate;
  NSArray *tableDataArray;
}

@property (nonatomic, retain) NSArray *tableDataArray;

- (IBAction)refreshXMLFeed:(id)sender;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil tableDataSource:(NSArray*)tableData;

@end

RootViewController.m:

#import "CustomCell.h"
#import "MyAppDelegate.h"
#import "RootViewController.h"
#import "DetailViewController.h"

@implementation RootViewController
@synthesize tableDataArray;

- (void)viewDidLoad {
  [super viewDidLoad];
}

//Override the default initWithNibName method
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil tableDataSource:(NSArray*)tableData {
  if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
    // Custom initialization
    tableDataArray = [tableData retain];   
  }
  return self;
}

-(void)viewWillAppear:(BOOL)animated {
  appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];    
  [super viewWillAppear:animated];
  //Set the colour of the navigationController and add buttons
  self.navigationController.navigationBar.tintColor = [UIColor blackColor];

  //Add the refresh button
  UIBarButtonItem* refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshXMLFeed:)];
  [self.navigationItem setLeftBarButtonItem:refreshButton animated:YES];
  [refreshButton release];  
}

#pragma mark Table

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return [self.tableDataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
  CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];
  if (cell == nil) {
    NSArray *cellNib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    for (id oneObject in cellNib) {
      if ([oneObject isKindOfClass:[CustomCell class]]) {
        cell = (CustomCell *)oneObject;
      }
    }
  }

  NSUInteger row = [indexPath row];
  NSDictionary *rowData = [self.tableDataArray objectAtIndex:row];
  cell.colorLabel.text = [rowData objectForKey:@"Type"];
  cell.nameLabel.text = [rowData objectForKey:@"Name"];
  UIImage *image = [UIImage imageNamed:[rowData objectForKey:@"Icon"]];
  cell.image = image;
  return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  NSString *selectedRow = [tableDataArray objectAtIndex:indexPath.row];

  DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]];
  detailViewController. selectedRow = selectedRow;
  [self.navigationController pushViewController:detailViewController animated:YES];

  UIBarButtonItem *backButton = [[UIBarButtonItem alloc] init];
  backButton.title = @"Back";
  self.navigationItem.backBarButtonItem = backButton;
  [backButton release];  
  [detailViewController release];
  detailViewController = nil;
}

#pragma mark Refresh

- (void)refreshXMLFeed:(id)sender {
  NSArray *tableControllersData = [appDelegate getData];
  [self.tableView setDataSource: tableControllersData];
  [self.tableView reloadData];  
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc { 
    [super dealloc];
}

@end

Upvotes: 0

Views: 5083

Answers (2)

Matt Long
Matt Long

Reputation: 24476

You should only be setting your data source once and it should not be an NSArray. The data container from which you pull your records can change, but the data source should always be the same. In most cases the data source should just be your view controller. Then your view controller should implement the methods in the UITableViewDataSource protocol including:

– tableView:cellForRowAtIndexPath:  required method
– numberOfSectionsInTableView:
– tableView:numberOfRowsInSection:  required method
– sectionIndexTitlesForTableView:
– tableView:sectionForSectionIndexTitle:atIndex:
– tableView:titleForHeaderInSection:
– tableView:titleForFooterInSection:

An NSArray doesn't respond to any of these methods which is why you are getting the unrecognized selector message. You have to implement them yourself.

You should familiarize yourself with the Table View Programming Guide to understand how to effectively use table views.

Best regards.

UPDATE: Here's a little code that might help you. In your RootViewController instantiate the NSArray with alloc/init in the -viewDidLoad. Call it items:

- (void)viewDidLoad;
{
    [super viewDidLoad];
    items = [[NSArray alloc] init];
}

Then implement your table view's data source delegates like this:

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return [items count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return 1;
}

Then you need to implement your cellForRowAtIndexPath:

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

    cell = [tv dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"] autorelease];

    }

    // Get your item from the items array here
    NSDictionary *item = [items objectAtIndex:[indexPath row]];
    NSString *text = [item valueForKey:@"text"];

    [[cell textLabel] setText:text];

    return cell;

}

This code assumes that the objects in your NSArray are NSDictionaries. If you are using some custom object, cast the object at that index path to your custom type and then use it's fields.

When you have new data available and need to reload your table view, you will simply re-allocate your items NSArray and then call reloadData on the tableview. Say you have a reload occurring like this:

- (void)didReciveNewData:(NSArray*)newItems;
{
    if (items) [items release], items = nil;
    items = [newItems copy];
    [tableView reloadData];
}

This will cause the table view to query its view controller for the number of rows to display and the cells for each row again which are provided by accessing the count and contents of the NSArray.

HTH.

Upvotes: 3

mml
mml

Reputation: 61

I'm guessing your data is loading asynchronously in your getData method (if you aren't you should be), which is updating/invalidating the reference to the datasource when the ui least expects it, causing crashes when the ui attempts to render with a stale pointer to its data.

Just make sure you never modify the contents of the tablecontrollersdata from a different thread.

or maybe you're trying to use coredata, in which case, i have no idea.

Upvotes: 0

Related Questions