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


When returning to a previous View Controller, I want to reinitialize the variables in that view controller(previous 1)


So the title sums up my question pretty much.

I have 3 view controllers: VC1, VC2, VC3

Depending on what button is click in VC1, I set a certain boolean variable to true and go to VC2. Depending on what button i click in VC2, I set a different boolean variable to True. I then display certain things in VC3 based on the two buttons that were clicked.

So now my problem is that when I navigate back from VC3 to VC2 for example, my variables are not Re-initialized. So if i click a different button other than the one i clicked the first time, I get the same data as before because although the new variable associated with the new button I clicked is set to true, the previous button I clicked associated with the first variable in VC2 is still true. As a result, I get the same data in VC3 as the first round.

I want to reinitialize my variables when i navigate backwards. How should i do this?

Thank You for your time and effort! Youseef

3 Answers

Faisal Alsheikh
Faisal Alsheikh
8,841 Points

Instead of using viewDidLoad, try using viewDidAppear

Hey Faisal,

Thanks for replying.

The thing is I don't use viewDidLoad in the first place. I just have regular functions that I Call on when a button is clicked. I can't use ViewDidLoad nor View Did Appear because the variables are global and I need them in other classes.

Faisal! Thank you my man. Your suggestion worked

So what I did was I reset the variables declared globally inside the 'viewWillAppear' method. This way i have my variables globally and initialized to start, and when the viewController is revisited (view appeared), my variables are reset to the same values.

Thank You for your help!

Faisal Alsheikh
Faisal Alsheikh
8,841 Points

Maybe it would help if your provide us with the source code or copy and paste the code through the tools used in the forum

Faisal Alsheikh
Faisal Alsheikh
8,841 Points

Great :) glad that helped. Coding rocks