Suppose , We have 3 ViewControllers called ViewControllerA , ViewControllerB , ViewControllerC in our UINavigationController
. To be specific , ViewControllerA is the RootViewController
and ViewControllerB and ViewControllerC are pushed on it. So, Currently ViewControllerC is on the Top and visible to user.
I want to return to ViewControllerA by calling [self.navigationController popToRootViewControllerAnimated:YES];
method and pass some data to ViewControllerA from here. I have to update some UI according to the data passed from ViewControllerC.
If I had to return data from ViewControllerB , then I could implement custom protocol/delegate. But what can be a good approach in the situation described above ?
Thanks in advance for your help.
You can try NSNotificationCenter as shown below.
Example:
In your ViewControllerA.m
-(void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataReceived:) name:@"passData" object:nil];
}
-(void)dataReceived:(NSNotification *)noti
{
NSLog(@"dataReceived :%@", noti.object);
}
In your ViewControllerC.m
-(void)gotoHome
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"passData" object:[NSDictionary dictionaryWithObject:@"Sample Data" forKey:@"dataDic"]];
[self.navigationController popToRootViewControllerAnimated:YES];
}
Here you can do with delegate methods
This is your root ViewController to call delegate methods
#import "ThirdViewController.h"
#import "SecondViewController.h"
@interface ViewController ()<ThirdViewControllerDelegate>
@end
@implementation ViewController
#pragma mark -
#pragma mark ThirdViewController Delegate Method
Implementation of delegate methods in your Root ViewController
-(void)didSelectValue:(NSString *)value{
NSLog(@"%@",value);
}
Pass the last Vc delegate to the next ViewController
-(void)gotoSeconddVc{
SecondViewController *vc2=[[SecondViewController alloc]init];
vc2.lastDelegate=self;
[self.navigationController pushViewController:vc2 animated:YES];
}
#import "ThirdViewController.h"
@interface SecondViewController : UIViewController
@property(nonatomic,retain) id <ThirdViewControllerDelegate> lastDelegate;
@end
-(void)gotoThirdVc{
ThirdViewController *vc3=[[ThirdViewController alloc]init];
vc3.delegate=self.lastDelegate;
[self.navigationController pushViewController:vc3 animated:YES];
}
Implementation of last viewcontroller
@implementation ThirdViewController
-(void)btnDoneClicked{
[self.navigationController popToRootViewControllerAnimated:YES];
[self.delegate didSelectValue:strValue]; //call delegate methods here
}
The best approach is to separate shared information in a different class (I suggest, it will be some model class). Just store the same instance of model class in both view controllers and update them whenever model class changes. Use notifications, KVC or ask model state every viewDidAppear: method.