In Objective-C, how do you declare/use a global variable?

10,225

Solution 1

Objective-C is a superset of C, so just do it the C way:

int globalX = 100;

And header file:

extern int globalX;

Solution 2

You do it exactly the way you would in C. Here's a simple example:

int myGlobal = 3;

Solution 3

Hope this's more clearly answer. In my case, I want to create a global class but:

I DONT'T WANT:

[GlobalResource shareInstance].bgrMenuFileName;

I WANT:

R.bgrMenuFileName

Do somethings like this! In GlobalResource.h file:

@class GlobalResource;

extern GlobalResource * R;

@interface GlobalResource: NSObject
+ (void) loadGlobalResources;
@end

In GlobalResource.m file:

// you must redeclare R 
GlobalResource *R;
// then init it

@implementation GlobalResouce
+ (void) loadGlobalResources
{
     R = [[GlobalResource alloc] init];
}
- (id)init
{
     self = [super init];
     if (self) {
          // your init
     }
     return self;
}
@end

Then, call loadGlobalResources when your app load:

[GlobalResource loadGlobalResources];

and import to Prefix.pch for using R anywhere in your project.

#import "GlobalResource.h"

Use it:

CCSprite *s = [CCSprite spriteWithFile:R.bgrMenuFileName];
//...
Share:
10,225
futurevilla216
Author by

futurevilla216

Updated on June 06, 2022

Comments

  • futurevilla216
    futurevilla216 about 2 years

    I have been researching this problem for a long time, and I can't seem to find the answer to this question. I am fairly new to iPhone programming, so sorry if this is a stupid question. If anyone has just specific code to post showing how this can be done, that will be very helpful.