Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Using the app delegate to house global variables

Is it bad practise to house variables that I want to be accessible from all classes in the app delegate and get them via [[UIApplication sharedApplication] delegate] someProperty]

like image 964
JoshDG Avatar asked Oct 05 '13 15:10

JoshDG


2 Answers

The real solution to your question isn't to replace one form of global state with another (i.e. singletons).

What you should be doing is putting state within "model" classes that are instantiated inside your app delegate, and then passing them down to the parts of your application that need them (e.g. view controllers), thereby eliminating your global state problem entirely.

like image 76
Shaggy Frog Avatar answered Oct 20 '22 08:10

Shaggy Frog


Its generally not a good practice to load up your AppDelegate as a container for app-wide variables in this way. It can quickly get unwieldy.

A common practice is to define some singleton objects, as follows:

+ (instancetype)shared
{
    static dispatch_once_t onceToken;
    static MyServiceClient* instance;

    dispatch_once(&onceToken, ^  //Use GCD to make a singleton with thread-safety
    {
        instance = [[self alloc] init];
    });
    return instance;
}

You can then provide these objects as parameters to your classes that require them as collaborators.

Use Dependency Injection

Note though that singleton can be considered an anti-pattern. If you inject these singletons into classes that require them its not too bad, however it's definitely not recommend to hard-wire them (unfortunately, also a common practice), as this promotes too-tight coupling, cohesion and requires complicated swizzling in order perform unit tests.

Another approach is to use dependency injection, in which case the objects need not even be singletons, in most cases. You can instantiate an object-graph of collaborating components for a given use-case that will come and go as needed. This has the benefit of using less memory on resource constrained devices.

Its a common misconception that you need a library to use dependency injection. You don't. It can help though. I created a dependency injection container called Typhoon.

Notifications

Another way of achieving loose collaboration between classes is to use notifications.

like image 27
Jasper Blues Avatar answered Oct 20 '22 08:10

Jasper Blues