Reputation: 133
I have two view controllers, FirstViewController and FourthViewController. FirstViewController is my initial view controller. I present FourthViewController with
UIViewController *fourthController = [self.storyboard instantiateViewControllerWithID:@"Fourth"];
[self presentViewController:fourthController animated:YES completion:nil];
Then, in FourthViewController's .m I'd like to change the text of a UILabel in FirstViewController. So I use
UIViewController *firstController = [self.storyboard instantiateViewControllerWithID:@"First"];
firstController.mainLab.text = [NSMutableString stringWithFormat:@"New Text"];
However, after I use
[self dismissViewControllerAnimated:YES completion:nil];
I find that my mainLab's text has not updated. Does anyone know why?
Upvotes: 2
Views: 642
Reputation: 436
If you want to update the label on first screen and nothing else then go for notifications. It's better rather you write the delegate. Because you want to update only label text thats it.
Upvotes: 0
Reputation: 34265
When you are calling this line from FourthViewController.m you are actually creating a new instance of FirstViewController, rather than using the already created one.
UIViewController *firstController = [self.storyboard
instantiateViewControllerWithID:@"First"];
You can tackle this in two ways.
post a notification from FourthViewController when label text need to be changed.
[[NSNotificationCenter defaultCenter] postNotificationName:@"updateLabel"
object:self];
In your FirstViewController viewDidLoad
methodcreate an observer that waits for this notification to get fired.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(updateLabelCalled:)
name:@"updateLabel"
object:nil];
Implement updateLabelCalled:
and update label.
- (void) updateLabelCalled:(NSNotification *) notification
{
if ([[notification name] isEqualToString:@"updateLabel"]){
//write code to update label
}
}
It is already explained here in stackoverflow. The basic idea is you create a FourthViewController delegate, and create a delegate method to updateLabel. FirstViewController should implement this method.
Upvotes: 3