在关闭控制器时将值传递给父控制器

时间:2011-07-07 05:50:22

标签: iphone objective-c uiviewcontroller presentmodalviewcontroller dismiss

我想将数据发送到parentviewcontroller,但以下代码崩溃了。给我解决方案

Post *vc;
vc.abc =@"Comment Conttroller";
[self.parentViewController dismissModalViewControllerAnimated:YES];

这里,Post是我调用presentViewController:animated:completion方法的控制器名称。

3 个答案:

答案 0 :(得分:21)

将其放在viewDidLoad

中的父控制器中
// get register to fetch notification  
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(yourNotificationHandler:)
                                      name:@"MODELVIEW DISMISS" object:nil];
// --> Now create method in parent class as;
// Now create yourNotificationHandler: like this in parent class
-(void)yourNotificationHandler:(NSNotification *)notice{
    NSString *str = [notice object];
}

将以下内容放在您的子课

-(void)dissmissModelView{

    [self dismissModalViewControllerAnimated:YES];
    NSLog(@"DismissModalviewController");

    //raise notification about dismiss 
    [[NSNotificationCenter defaultCenter] 
          postNotificationName:@"MODELVIEW DISMISS" 
                        object:@"Whatever you want to send to parent class"];  
}

只要模型视图被解除, yourNotificationHandler 就会被执行,而您传递的任何内容都会在您的父类中获取。请问是否还需要澄清一下。

答案 1 :(得分:1)

ParentViewController

中的.h文件中
NSString *strABC;

ParentViewController

中创建以下功能
-(void)setString:(NSString *)strEntered{
    strABC=strEntered;
}

现在在Post视图控制器中这样做:

ParentViewController *objSecond = 
  [[ParentViewController] initwithNibName:@"parentView.xib" bundle:nil];

[objSecond setString:@"Comment Controller"];
[self.navigationController pushViewController:objSecond animated:YES];
[objSecond release];

现在,在 secondViewController viewWillAppear方法中写下这个。

-(void)viewWillAppear:(BOOL)animated{
      lblUserInput.text = strABC;
}

请仔细检查拼写错误。希望这有帮助。

如果您没有使用UINavigationContoller,那么您可以这样做。

SecondViewControler *objSecond = 
  [[SecondViewController] initwithNibName:@"secondview.xib" bundle:nil];
[objSecond setUserInput:txtUserInput.text];
[objSecond viewWillAppear:YES];
[self.view addSubview:objSecond];
[objSecond release];

答案 2 :(得分:0)

vc似乎没有被初始化。

你可以这样做,

vc = (Post *)self.parentViewController;
vc.abc = @"Comment Conttroller";
[vc dismissModalViewControllerAnimated:YES];

由于您要影响的视图控制器是parentViewController,因此您应该能够投射和设置abc属性。