Issue with global variables in Objective-C

Total Post:23

 972  View(s)
Rate this:

Learn this paragraph that is taken from the Cocoa programming documentation:

You will be registering, reading, and setting defaults in several classes in your application. To make sure that you always use the same name, you should declare those strings in a single file and then simply #import that file into any file in which you use the names. There are several ways to do this. For example, you could use the C preprocessor’s #define command, but most Cocoa programmers use global variables for this purpose.

Is this really the correct best practice? Global variables? That seems insane to me – counter to everything I’ve ever been taught.

Would a better design be a simple Singleton class with these defined? Or is it really the correct best practice to go global? Is there a better pattern than either, given that many people consider Singletons to be globals in a pretty dress?

  1. Post:214

    Re: Issue with global variables in Objective-C

    According to the cocoa documentation I understand that global variables or a singleton classes will accomplish the same thing here because both can be used to turn 'key' names in Cocoa that would not throw a compiler error if it's misspelled into a compiler error. That's the main purpose. Global variables are a bit easier though seeing as it requires less typing.
    Instead of doing this:

    [arrayObj setObject:newObj forKey:MyGlobalVariableKeyName];

    we can do something along the lines of:

    [arrayObj setObject:newObj forKey:[[MySingletonVariableClass getInstance] myVariableKeyName];

    Global variables are essentially less typing for the same effect.