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

I studied this problem for a long time, and I can not find the answer to this question. I'm new to programming on the iPhone, so sorry if this is a stupid question. If someone only has specific code to post showing how this can be done, this will be very helpful.

+4
source share
3 answers

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

int globalX = 100; 

And the header file:

 extern int globalX; 
+9
source

You do this exactly the same as in C. Here is a simple example:

 int myGlobal = 3; 
+2
source

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

I DO NOT WANT:

 [GlobalResource shareInstance].bgrMenuFileName; 

I WANT:

 R.bgrMenuFileName 

Do something like that! In the GlobalResource.h file:

 @class GlobalResource; extern GlobalResource * R; @interface GlobalResource: NSObject + (void) loadGlobalResources; @end 

In the 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 application loads:

 [GlobalResource loadGlobalResources]; 

and import into Prefix.pch to use R anywhere in your project.

 #import "GlobalResource.h" 

Use it:

 CCSprite *s = [CCSprite spriteWithFile:R.bgrMenuFileName]; //... 
+1
source

Source: https://habr.com/ru/post/920835/


All Articles