tags:

views:

1761

answers:

2

i have a global variable in 1 of the class like classA.h

const NSString *global;

classA.m

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

and in another class i want to call this global variable

classB.m

import "class.h"

NSLog(@"%@",global);

but it doesnt work,i know when i jus assigned a value directly to my global variable instead of from another variable it will work but can somebody show me how to make it achieve from a array?

+2  A: 

In the header, use:

extern const NSString *global;

and in the implementation (.m):

const NSString *global;

The "extern" reference tells all including files that the variable exists, but it's declared elsewhere. Finally, in your implementation file, you put the actual declaration.

NilObject
It's best to use NSString * const global, since then the compiler won't warn you when passing a const pointer to an NSString as a parameter to a method expecting a non-const pointer to an NSString.
dreamlax
thanks NilObject but i think the problem i had is how assigned the value to the global variable from a array object,can show me some of the example
issac
Your example works with my changes to the global variable declaration, but you're not retaining a reference to the object, so it may be destroyed if the array goes out of existence.
NilObject
A: 

You cannot do this like that.

const NSString *global;
NSString const *global;

both mean a pointer (that can be changed) to a constant NSString object. In Objective-C constant objects make no sense. The compiler cannot enforce the constness of objects. It can not know wether a method changes the internal state of an object or not. Also all the classes in the library always take pointers to non-constant objects as parameters for their methods, so having any const object pointers will cause a lot of warnings.

On the other hand there are constant pointers to objects which are declared like this:

NSString * const global;

This means the pointer points to a regular NSString object, but it’s value cannot be changed. This means that you also have to 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 there is no way to specify a compile-time constant object thats required for the initialization. And in this case it is a true constant - string literals are immutable by definition.

But in your case you can do away with the const. You want to change the pointer later so it cannot be a NSString * const. If you insist on a global you’d just have to make it a regular NSString *. On the other hand - globals are evil. You should change your design so you don’t need it.

Sven