Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

How do i set a @property of another class?

My interface is more complicated than this, but for simplicity, i’m going to describe is at this: I have 2 views.The app loads, the first view opens up and there is a textfield and a button. The user hits the button and brings them to the second view where there is another button and another textfield. What i want to do is have the user enter a value in the second view textfield, and when they hit the button to return to the first view, give the first views textfield the value that the second view textfield had.

So basically, i have the second views textfield stored in a variable called “actualAverage” and when the second view button is hit, this action fires:

- (IBAction)backButton:(id)sender {
    if (haveValueToReturn) {

        //set the firstviewtext box to the percent somehow
        FirstViewController *firstViewControllerObject = [self.storyboard instantiateInitialViewController];
        firstViewControllerObject.string = [[NSString alloc] initWithFormat:@"%f", actualAverage];
    }

    //switch the views
    [self dismissViewControllerAnimated:YES completion:nil];
}

Everything logically and syntactically appears OKAY, but when i run it, the value set to firstViewControllerObject.string is nil. Every time and i have no idea why… Any help would be very much appreciated

2 Answers

The reason why it doesn't work is because instantiateInitialViewController returns a new copy of the initial view controller, i.e. a different one than the one you are displaying.

The most straightforward way (not the best, but simple) is to have a weak property, say firstVC in your second view controller, and set it to the first view controller's self from within first view controller's prepareForSegue. Then, before you dismiss your second view, you can simply access the string property via the reference from within your second view controller.

Did you already import the header file from the other class into your class that you're trying to use?