Search code examples
objective-cios4xcode4uiviewcontrollerxcode4.2

How to access other viewcontrollers variables/properties in xcode


I know similiar questions have been asked before, but please bear with me as I am totally new at Objective C (have good knowledge on C).

My case is that I have a tab bar controller with two windows. When I press a button in "second" I change a variable changeName. I want to use the value of changeName in my "first" view controller but stumbled on to some problems:

To reach the other viewcontroller I found this from SO (unfortunately I forgot where):

-(NSString *)newName{

// Create a UIStoryboard object of "MainStoryBoard_iPhone" named storyboard
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:(NSString *)@"MainStoryBoard_iPhone" bundle:(NSBundle *)nil];

// Create a UIViewController object of the wanted element from MainStoryBoard_iPhone
UIViewController *secondview = [storyboard instantiateViewControllerWithIdentifier:(NSString *)@"secondBoard"];

return secondview.changeName;
}

Which I have in my first.m. MainStoryBoard_iPhone is the name of the .xib/storyboard-file.

but no. Error says

Property 'changeName' not found on object of type 'UIViewController *'

In my second.h I have

 @property (readwrite, retain) NSString *changeName;

and in second.m

 @synthesize changeName;

All help is appreciated, but please keep in mind that I have only used OOP for two days. Thank you all in advance

EDIT: And what input should I have here?

 - (void)viewDidLoad
{
[super viewDidLoad];
mylabel.text = Name; // or [mylabel.text Name] or something? 
}

Solution

  • You need to cast the view controller returned to your customized second view controller (as UIViewController does not have the property changeName).

    So do the following :

    // Create a UIViewController object of the wanted element from MainStoryBoard_iPhone
    SecondViewController *secondview = (SecondViewController *)[storyboard instantiateViewControllerWithIdentifier:(NSString *)@"secondBoard"]; 
    

    I assume SecondViewController is the name of your second controller.