views:

425

answers:

2

I have an instance of UIViewController displaying a list of items. When the user selects an item I need to create a new instance of UIViewController (populated by a different list of items) and show it. At the moment I'm calling the constructor from within the didSelectRowAtIndexPath method

    RootViewController *rootViewController = [[RootViewController alloc]initWithStyle:UITableViewStylePlain];
UIViewController *targetViewController = rootViewController;
[[self navigationController] pushViewController:targetViewController animated:NO];

But instead of creating a new object it reuses the current one: the new view contains items from the new list as well as from the previous list. So how do I create a new instance of RootViewController from within itself?

A: 

You are creating and presenting a new view controller, your problem is elsewhere.

Where are you keeping the data for the table?

Your code does make a new instance, but it's very telling that after creation you are not telling the new view controller what to display - this means that you are getting the data from some more global source, which you must have merely appended the new data onto.

Kendall Helmstetter Gelner
The data is an xml file. I call a method to parse the xml and populate the list. Depending on the value of the arguments I load different xml lists. But the old ones stay.. hmm...
Pavel
A: 

Really vaguely:

1) Import your 2nd level header file into this implementation file. Back in the 2nd level have getters/setters. In your 1st level add another method, -(BOOL)set2ndLevelDataBasedOnXMLSource:(id)source in this method set the appropriate instance variables and do computations to set the data.

2) Your code in didSelectRow should look like:

    if(!rootViewController) {
RootView *rootViewController = [[RootView alloc] initWithstyel...]; }

BOOL result = [self set2ndLevelDataBasedOnXMLSource:_Source_];

if(result) {
[[self navigationController] pushViewController:targetViewController animated:NO]; }

Then you could refactor it:

if([self set2ndLevelDataBasedOnXMLSource:_Source_])  {
[[self navigationController] pushViewController:targetViewController animated:NO]; }

3) in -(BOOL)set2ndLevelDataBasedOnXMLSource:(id)source {

I have:

NSUInteger result;
if(source == true) {

2ndLevelController.section1data = [source (parse for)...];

2ndLevelController.section2data = [source (parse for ...)];

...

result = 1; }
else { result = 0; }

return result;

4) in my 2nd Level, under viewWillDisappear I set all those instance variables to nil (they're mutable arrays)

That's how I did it.

JoePasq