I know this is a basic questing but I am just not finding a good answer. I have a app with multiple view controllers and I have noticed that if a create a variable and take action on it in one controller:
int foo = 0;
foo =+ 1;
I can declare the variable in another controller without initializing it’s value it will carry the value it was last set to in the previous view controller:
int foo;
if (foo == 1)
doSomething;
I have used this to my advantage for keep track of the current player in a multi player game etc… using the data in multiple controllers as their views are loaded and removed. I am new to Obj C and based on what I have been reading this does not seem like the right way to to things.
So here is my question, is this a safe way to pass data between controllers and if not what should I be doing?
This is not a safe way to be passing information between controllers. If you are using this in your application, and it’s working, I am actually very surprised.
The proper way to do this is to actually pass the value you need from one controller to the other. The example below uses the Application Delegate to store the value, and then each controller reads/writes to it… it’s just an example, be careful about about using the Application Delegate as a repository for what become effectively global variables. Setting up lots of variables in the Application Delegate for use in this manner will make your application difficult to maintain.
In your App Delegate.h
In your App Delegate.m
Then in the controller where you want to set the value:
Then in the controller where you want to read the value:
Edited: forgot the @synthesize.
Edited: typed the return from the delegate singleton method, based on a suggestion from Kenneth Ballenegger, to eliminate the compiler warnings.