0

I inherited an iOS application that shares variables throughout the project by doing the following:

[AppDelegate sharedDelegate].myVal = myVal;

This makes it easy to share data between view controllers, but it just feels wrong. I am not able to properly articulate and explain to the previous developer why though.

Why is this a bad programming/design decision to pass around data in this manner?

Atma
  • 29,141
  • 56
  • 198
  • 299
  • That's very similar to using global variables: http://programmers.stackexchange.com/questions/148108/why-is-global-state-so-evil – DrummerB Jan 29 '14 at 18:33
  • A plain english explanation is: "It's like writing shopping lists on your home instead of the piece of paper you carry with" – Stephen J Jan 29 '14 at 19:23

4 Answers4

2

Reason why AppDelegate is not good for storing general purpose variables:

  1. Centralising data
  2. Makes it a globally accessible variable
  3. Was not design to dealt as any kind of data manager
  4. Can provide to a spaghetti code

More:

This article might be worth reading

I also like this post

Community
  • 1
  • 1
Julian
  • 9,299
  • 5
  • 48
  • 65
0

I would say that it's not the responsibility of the AppDelegate. The AppDelegate is an object that gets notified for certain app level state changes. See: What is the AppDelegate for and how do I know when to use it?

If you want to have settings that you can globally access in your whole project, I would advice a constants file. See: Constants in Objective-C

Community
  • 1
  • 1
gitaarik
  • 42,736
  • 12
  • 98
  • 105
0

Can you do it? Yes. Are there better ways to do this? Yes.

You can create a shared instance on a root view controller that is the main application view controller or even create an [ICEGlobals sharedInstance] that's basically an extension of NSObject if you really need shared access to some variables. However, this is frowned upon unless absolutely needed because from an organizational stand point you should rarely have to do this. You should be passing references to new view controllers and doing things that way.

GregP
  • 1,584
  • 17
  • 16
0

The AppDelegate is supposed to be something that responds to application-level events that are not specific to your app, such as applicationWillEnterForeground:. So this means it could make sense to use it properties that deal with or are related to application state/lifecycle. For example, you might add a BOOL property called didEnterBackgroundAtLeastTwice.

If you're just storing something completely unrelated, like an int playerLives, this makes less sense because there is probably another singleton you should make to handle that app-specific code and data.

Michael Chinen
  • 17,737
  • 5
  • 33
  • 45