Home > DeveloperSection > Forums > Issue with global variables in Objective-C
zack mathews
zack mathews

Total Post:23

Posted on    December-15-2015 12:25 AM

 iPhone iPhone  Ios  Objective C 

 1 Reply(s)
 499  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?

Tarun Kumar

Total Post:213

Posted on    December-15-2015 10:53 PM

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.

Don't want to miss updates? Please click the below button!

Follow MindStick