0
votes

So I thought I understood how to pass data between ViewControllers until today. I have 4 UITableViewControllers VC1, VC2, VC3 and VC4.

When in VC1 you can make a selection by clicking trough VC2 to VC4. VC2, VC3 and VC4 are related to each other, so if you select A in VC2 you only see data in VC3 that is related to A, and so on.

if you have only 2 VC's you'll normally do something like this:

{
    SecondViewController *VC2 = [[SecondViewController alloc]init];
    VC2.VC1 = self;  
    [self.navigationController pushViewController:svc animated:YES];
}

(and off course use VC1 as a property in VC2)

But in this case I want to do something like VC4.VC1 instead of VC2.VC1, but this makes no sense as I need to go from VC2 to VC3 to VC4 and use these selected values in VC1. (in VC1 I use these selected values from VC2, VC3 and VC4 plus add some additional information and save that in a separate object.

I tried to pass the data back from VC4 like this:

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 firstViewController *VC1 = [[firstViewController alloc] init];
   .....   
  [VC1 passSelectedVC2:CV2 selectedVC3:VC3 selectedVC4:VC4];

  [self.navigationController popToRootViewControllerAnimated:YES];
  ....
  }

But that does not work. I have added NSLOG in passSelectedVC2 method to check, but all passed data stays null (and I also do not want to use firstViewController *VC1 = [[firstViewController alloc] init];in didSelectRowAtIndexPath, as it doesn't feel right)

I hope above is a bit clear, otherwise please let me know.

2
You can't do that. You are instantiating a brand new VC1, not the one in the navigation stack. Instead get your VC1 from the stack. [[self navigationController] viewControllers] this is your navigation stack, pick the vc you need by its array index.Desdenova
Hi, so using this I would be using the actual VC instead of creating a new one?Eloy

2 Answers

1
votes

I think you've just experienced the main problem with ignoring the 'M' part of MVC.

At this level of complication (or earlier), I'd really suggest making your data model an independent object that's accessible as a singleton or by requesting it from your app delegate. That way, each controller can get what it needs as it's loading its view rather than depend on a baroque chain of parameter passing and property updating.

0
votes

changing firstViewController *VC1 = [[firstViewController alloc] init]; into firstViewController *VC1 = [[[self navigationController] viewControllers]objectAtIndex:0]; solved my issue.