How to save global variables in iOS development?

I have an iOS application with several controllers, each with its own xib files.

How to set a global variable with scope covering all controllers? Should I use NSUserDefaults and get data for each view every time?

+6
source share
3 answers

NSUserDefaults are for things that require stamina, i.e. You plan to store them between application launches. For temporary variables, consider using a singleton instance, such as the MySingleton class shown in this answer: fooobar.com/questions/3298 / ....

When you have this class, put your temporary variables as a property 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.

+7
source

In general, you want to avoid using global variables. If you need access to data that should be shared, there are two common approaches.

Put the values ​​in AppDelegate.

If you have only one or two common values, AppDelegate is an easy way to post shared content.

Access to AppDelegate can be obtained from your controllers as such:

 FooApp* appDelegate = (FooApp*)[[UIApplication sharedApplication] delegate]; 

Where FooApp is the name of your application class.

Create a singleton class.

Contaminating your AppDelegate with many common values ​​is not ideal and / or if you want these values ​​to be saved from session to session, creating a Singleton class that is supported by NSUserDefaults is another way to exchange values ​​between instances.

+10
source

Depending on your exact needs, you can learn and use the Singleton design template to create a kind 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.

+2
source

Source: https://habr.com/ru/post/912152/


All Articles