将一些数据传回给RootViewController iOS 7
假设我们在我们的UINavigationController
有3个ViewController叫做ViewControllerA,ViewControllerB,ViewControllerC。 具体来说,ViewControllerA是RootViewController
而ViewControllerB和ViewControllerC则是在它上面推送的。 所以,目前ViewControllerC是在顶部和用户可见。
我想通过调用[self.navigationController popToRootViewControllerAnimated:YES];
返回到ViewControllerA [self.navigationController popToRootViewControllerAnimated:YES];
方法并从这里传递一些数据到ViewControllerA。 我必须根据从ViewControllerC传递的数据更新一些用户界面。
如果我不得不从ViewControllerB返回数据,那么我可以实现自定义协议/委托。 但是,在上述情况下,什么是一个好的方法?
在此先感谢您的帮助。
你可以尝试如下所示的NSNotificationCenter,
例:
在你的ViewControllerA.m中
-(void)viewDidLoad { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataReceived:) name:@"passData" object:nil]; } -(void)dataReceived:(NSNotification *)noti { NSLog(@"dataReceived :%@", noti.object); }
在你的ViewControllerC.m中
-(void)gotoHome { [[NSNotificationCenter defaultCenter] postNotificationName:@"passData" object:[NSDictionary dictionaryWithObject:@"Sample Data" forKey:@"dataDic"]]; [self.navigationController popToRootViewControllerAnimated:YES]; }
谢谢!
在这里你可以使用委托方法
//这是你的根ViewController来调用委托方法
#import "ThirdViewController.h" #import "SecondViewController.h" @interface ViewController ()<ThirdViewControllerDelegate> @end @implementation ViewController #pragma mark - #pragma mark ThirdViewController Delegate Method
//在你的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]; }
最后一个viewcontroller的实现
@implementation ThirdViewController -(void)btnDoneClicked{ [self.navigationController popToRootViewControllerAnimated:YES]; [self.delegate didSelectValue:strValue]; //call delegate methods here }
最好的办法是分享不同类别的共享信息(我build议,这将是一些模型类)。 只需在两个视图控制器中存储相同的模型类实例,并在模型类更改时更新它们。 使用通知,KVC或询问模型状态每个viewDidAppear:方法。