Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Variables in Cocoa/Objective-C?

Tags:

According to Cocoa Programming for Mac OS X, 3rd Edition, on page 202 (chapter 13):

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?

like image 944
John Rudy Avatar asked Dec 03 '08 18:12

John Rudy


Video Answer


2 Answers

Just to be clear, the recommendation is to create immutable global variables instead of in-line string constants (hard to refactor and no compile-time checking) or #defines (no compile-time checking). Here's how you might do so...

in MyConstants.h:

extern NSString * const MyStringConstant;

in MyConstants.m:

NSString * const MyStringConstant = @"MyString";

then in any other .m file:

#import "MyConstants.h"

...
[someObject someMethodTakingAString:MyStringConstant];
...

This way, you gain compile-time checking that you haven't mis-spelled a string constant, you can check for pointer equality rather than string equality[1] in comparing your constants, and debugging is easier, since the constants have a run-time string value.

[1] In this use, you are essentially using the pointer values as the constants. It just so happens that those particular integers also point to strings that can be used in the debugger

like image 68
Barry Wark Avatar answered Oct 26 '22 23:10

Barry Wark


Global variables or a singleton will accomplish the same thing here. Both can be used to turn 'key' names in Cocoa that won't 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:

[myArray setObject:theObject forKey:MyGlobalVariableKeyName];

You'd have to do something along the lines of:

[myArray setObject:theObject 
            forKey:[[MySingletonVariableClass getInstance] myVariableKeyName];

Global variables are essentially less typing for the same effect.

like image 40
Grant Limberg Avatar answered Oct 26 '22 23:10

Grant Limberg