I have an iOS application with several controllers, each with their own xib files.
How do I set a global variable with scope that spans all controllers? Should I use NSUserDefaults
and retrieve data for each view every time?
In general, you want to avoid using globals. If you need access to data that must be shared, there are two common approaches.
Put the values in your AppDelegate.
If you have only one or two shared values, the AppDelegate is an easy way to place shared content.
The AppDelegate can be accessed from your controllers as such:
FooApp* appDelegate = (FooApp*)[[UIApplication sharedApplication] delegate];
Where FooApp
is the name of your application Class.
Create a singleton class.
Polluting your AppDelegate with lots of shared values isn't ideal, and/or if you want these values to persist from session to session, creating a Singleton class that is backed by NSUserDefaults
is another way to share values across instances.
NSUserDefaults
are for things that require persistance, i.e. you are planning on storing them between app starts. For temporary variables, consider using a singleton instance, such as the MySingleton
class illustrated in this answer: https://stackoverflow.com/a/145164/108574 .
When you have this class, put your temporary variables as property
of this class for easy access. And when you need to access it, just call [MySingleton sharedSingleton].variable
.
Also check here: http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With