1

I am developing a game which needs variables that need to be accessed by different classes. I wanted to know if there is a way to make global mutable variables with Objective C?

sashkello
  • 17,306
  • 24
  • 81
  • 109
Tu Ch
  • 133
  • 1
  • 11
  • 2
    Why don't you encapsulate them in a class? You can make it a singleton if they're truly global. – Jordão May 31 '12 at 02:04

2 Answers2

2

There's no problem creating global mutable variables in Objective-C.

In a header file:

extern NSMutableArray *gMyArray;
extern NSMutableDictionary *gMyDictionary;

In your application delegate source file:

NSMutableArray *gMyArray;
NSMutableDictionary *gMyDictionary;

In applicationDidFinishLaunching:

gMyArray = [[NSMutableArray alloc] init];
gMyDictionary = [[NSMutableDictionary alloc] init];

Then just #import the header file in every source file you want to access the global.

EricS
  • 9,650
  • 2
  • 38
  • 34
2

The usual approach is to provide a singleton class which provides access to the required variables. And rather than exposing a raw variable that is mutated directly by the caller, you should really encapsulate the operations. Having true global variables creates too much coupling and is a bad code smell.

For example, a singleton lets you write this:

[[NetworkTrafficStats instance] addNetworkTraffic:bytes_sent];

which is much better to maintain than:

extern unsigned gTotalBytesSent;
//...
gTotalBytesSent += bytes_sent;

Worth reading:

Community
  • 1
  • 1
gavinb
  • 19,278
  • 3
  • 45
  • 60