Justin Copeland
Justin Copeland

Reputation: 1951

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?

Upvotes: 6

Views: 7445

Answers (3)

Alan
Alan

Reputation: 46813

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.

Upvotes: 10

Dream Lane
Dream Lane

Reputation: 1312

Depending on your precise needs you could learn about and use the Singleton design pattern to create a sort of database object that can be shared across all views. Read about iOS Singletons here.

This is how I accomplished what you are looking for in my iOS App.

Upvotes: 2

He Shiming
He Shiming

Reputation: 5819

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.

Upvotes: 7

Related Questions