问题
I want to send data to parentviewcontroller but the following code crashes. Give me the solution
Post *vc;
vc.abc =@"Comment Conttroller";
[self.parentViewController dismissModalViewControllerAnimated:YES];
Here, Post is the controller name from where I am calling the presentViewController:animated:completion
method.
回答1:
vc
doesn't seem to be initialized.
You can probably do this,
vc = (Post *)self.parentViewController;
vc.abc = @"Comment Conttroller";
[vc dismissModalViewControllerAnimated:YES];
Since the view controller you want to affect is the parentViewController
, you should be able to cast and set the abc
property.
回答2:
Put this in your parent controller in 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];
}
Put following to your child class where
-(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"];
}
as soon as model view get dismiss yourNotificationHandler get executed and whatever you pass as an objet will get fetch in your parent class. Please ask if still need some clarification.
回答3:
Take this in .h file in ParentViewController
NSString *strABC;
Make below function in ParentViewController
-(void)setString:(NSString *)strEntered{
strABC=strEntered;
}
Now In Post view controller do like this:
ParentViewController *objSecond =
[[ParentViewController] initwithNibName:@"parentView.xib" bundle:nil];
[objSecond setString:@"Comment Controller"];
[self.navigationController pushViewController:objSecond animated:YES];
[objSecond release];
Now, In secondViewController viewWillAppear
method write this.
-(void)viewWillAppear:(BOOL)animated{
lblUserInput.text = strABC;
}
Please check spelling mistakes as I've hand written this. Hope this help.
If you are not using UINavigationContoller
then you can do something like this.
SecondViewControler *objSecond =
[[SecondViewController] initwithNibName:@"secondview.xib" bundle:nil];
[objSecond setUserInput:txtUserInput.text];
[objSecond viewWillAppear:YES];
[self.view addSubview:objSecond];
[objSecond release];
来源:https://stackoverflow.com/questions/6606355/pass-value-to-parent-controller-when-dismiss-the-controller