将一些数据传递回RootViewController iOS 7

问题描述 投票:1回答:3

假设,我们在UINavigationController中有3个ViewControllers,名为ViewControllerA,ViewControllerB,ViewControllerC。具体来说,ViewControllerA是RootViewController,ViewControllerB和ViewControllerC被推到它上面。因此,目前ViewControllerC位于Top并且对用户可见。

我想通过调用[self.navigationController popToRootViewControllerAnimated:YES];方法返回ViewControllerA并从此处将一些数据传递给ViewControllerA。我必须根据从ViewControllerC传递的数据更新一些UI。

如果我必须从ViewControllerB返回数据,那么我可以实现自定义协议/委托。但在上述情况下,什么是一个好方法呢?

在此先感谢您的帮助。

ios objective-c uiviewcontroller uinavigationcontroller delegates
3个回答
3
投票

您可以尝试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];
}

1
投票

在这里你可以使用委托方法

这是您调用委托方法的根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);
}

将最后一个Vc委托传递给下一个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
}

0
投票

最好的方法是将不同类中的共享信息分开(我建议,它将是一些模型类)。只需在两个视图控制器中存储相同的模型类实例,并在模型类更改时更新它们。每个viewDidAppear:方法使用通知,KVC或询问模型状态。

© www.soinside.com 2019 - 2024. All rights reserved.