Problem with declaring a global variable in object c

I have a global variable in 1 class, for example classA.h

const NSString *global; 

classA.m

 global=[array objectAtIndex:0];//a array store sort of string 

and in another class I want to name this global variable

classB.m

 import "class.h" NSLog(@"%@",global); 

but it doesn’t work, I know when jus assigned the value directly to my global variable, and not from another variable, it will work, but can anyone show me how to achieve this from the array?

0
source share
2 answers

In the header use:

 extern const NSString *global; 

and in implementation (.m):

 const NSString *global; 

The extern link tells all files that the variable exists, but is declared elsewhere. Finally, in your implementation file, you place the actual declaration.

+3
source

You cannot do that.

 const NSString *global; NSString const *global; 

both mean a pointer (which can be changed) to a constant NSString object. In Objective-C objects, constants are meaningless. The compiler cannot ensure the constancy of objects. He cannot know that the method changes the internal state of the object or not. In addition, all classes in the library always accept pointers to mutable objects as parameters for their methods, so the presence of any const object pointers will cause a lot of warnings.

On the other hand, there are constant pointers to objects that are declared as follows:

 NSString * const global; 

This means that the pointer points to a regular NSString object, but its value cannot be changed. This means that you must also initialize the value of the pointer (it cannot be changed later). This is used to define constants. But this only works with NSStrings and string literals. For all other classes, it is not possible to specify the compile-time constant object needed for initialization. And in this case, it is a true constant. String literals are, by definition, immutable.

But in your case, you can do away with const . You want to change the pointer later so that it cannot be NSString * const . If you insist on a global youd, you just need to make it a regular NSString * . Globals, on the other hand, are evil. You must change your design so that you do not need it.

+1
source

All Articles