iOS: Using the app delegate to house global variables

大兔子大兔子 提交于 2020-01-02 01:35:47

问题


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]


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19199569/ios-using-the-app-delegate-to-house-global-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!