I have two view Controllers in my project ViewController
, SettingsView
. Here I am trying to update the ViewController\'s
label, when i
You have to implement protocols for that. Follow this:
1) In SettingView.h define protocol like this
@protocol ViewControllerDelegate
-(void) updateLabel;
@end
2) Define property in .h class and synthesis in .m class..
@property (nonatomic, retain) id <ViewControllerDelegate> viewControllerDelegate;
3) In SettingsView.m IBAction
-(IBAction)backToMain:(id) sender
{
[viewControllerDelegate updateLabel];
}
4) In ViewController.h adopt protocol like this
@interface ViewController<ViewControllerDelegate>
5) In viewController.m include this line in viewDidLoad
settingView.viewControllerDelegate=self
You are not exactly calling the correct vc
. This is because you are creating a new instance of that class and calling the updateLabel
of that instance.
You have a few options.
Either implement it as a delegate
callBack (delegate messagePassing, or delegate notification - however you want to call it) to notify that class instance to call the updateLabel
method.
Use the original instance VC
as a dependency injection
into the class that you are on right now, and use that instance to call the updateLabel
Use NSNotifications / NSUserDefaults to communicate between viewControllers and setup a notification system for your actions. This is quite easy, but not really great in the long run.
I would RECOMMEND option 1 (or) option 2.
Your label is not updating because , you are trying to call updateLabel
method with a new instance.
You should call updateLabel
of the original instance of viewcontroller from which you have presented your modal view.
you can use a delegate mechansim or NSNotification to do the same.
Delegate mechnaism would be clean. NSNotification is quick and dirty.
Simply declare like this in SettingsView class:
UILabel *lblInSettings;// and synthesize it
Now assign like below when you presenting Settings viewController:
settingsVC.lblInSettings=self.myLabel;
Then whatever you update in lblInSettings it will be present in MainView obviously.... no need for any delegate methods or updating methods.
Means if you assign at the time of dismissing like
lblInSettings.text=@"My new value";
then self.myLabel also will be updated.
Let me know if you have any queries?