Xcode - update ViewController label text from different view

I have two view Controllers in my project ViewController, SettingsView. Here I am trying to update the ViewController's label, when i click on the SettingsView's back button. NSLog is working fine, but the label is not updating... Please help me....

SettingsView.m

-(IBAction)backToMain:(id) sender {

  //calling update function from ViewController
    ViewController * vc = [[ViewController alloc]init];
    [vc updateLabel];
    [vc release];

  //close the SettingsView 
    [self dismissModalViewControllerAnimated:YES];
}

ViewController.m

- (void)updateLabel
{
    NSLog(@"Iam inside updateLabel");
   self.myLabel.text = @"test";
}

Could you please tell me whats wrong with my code? Thank you!


Solution 1:

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

Solution 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.