Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save global variables in iOS development?

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?

like image 244
Justin Copeland Avatar asked Apr 01 '12 00:04

Justin Copeland


2 Answers

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.

like image 200
Alan Avatar answered Sep 22 '22 16:09

Alan


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.

like image 29
He Shiming Avatar answered Sep 22 '22 16:09

He Shiming