In Objective-C, how do you declare/use a global variable?
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 h开发者_开发百科elpful.
Objective-C is a superset of C, so just do it the C way:
int globalX = 100;
And header file:
extern int globalX;
You do it exactly the way you would in C. Here's a simple example:
int myGlobal = 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];
//...
精彩评论