A static variable is not available from another class.

I have a static variable that I want to get from another class in the same project in X-Code. I declared it in the .h file and the .m file, gave it a value, and then when I turned to another class, I got an error message:

"Property 'xx' not found on object of type 'yy'"

i declared the variable as extern in .h and redefined it as the type of the variable in .m. I tried changing it to static in .h, but it still doesn't work. And yes, I imported the file containing the variable in case this is a problem.

Can anybody help me?

EDIT:

this is the code I'm using now:

source.h

static int anObject; @interface source : NSObject 

source.m

 static int a = 2 @implementation source 

destination.m

 # include "source.h" @implementation destination - (void) anObjectTestFunction { printf("%d", source.anObject); //the first version printf("%d", anObject); //second version } 

now after I switched to the second version, the variable anObject in destination.h can be obtained, but its value is not 2, it is 0. I want it to match the one I declared in source.h.

+4
source share
3 answers

I assume that the static variable declared in the .h file is outside of @interface . So something like:

 static NSString *myObjectTest = @"Test"; @interface MyObject : NSObject @end 

If so, you will not be able to access it using something like:

 MyObject *obj = [[MyObject alloc] init]; [obj myObject] 

or

 obj.myObject 

This is what the xx property gives you, not found on an object of type yy. This static variable is not a property of MyObject.

This static variable is available in this way myObjectTest while you import the .h file

Update See Chuck's comment below why this is a bad idea for this.

+8
source

You seem confused about what a static variable is. In other languages, such as Java or C ++, “static” can mean one of two things. In the field of files or functions, this means a variable attached to the file or functions that have existed for your program all your life. In the scope of a class, this means only a class variable.

C ++ has both definitions, Java has only the second definition, but Objective-C has only the first definition: a static variable can only be used where it was declared. There is no such thing as an “external static” variable because they are inconsistent. You probably need a global variable or a static variable with a class method to access it.

+2
source

Could this be a namespace problem? Try to fully qualify your access. Posting an extract from your code would really be useful, although I cannot clairvoyance :-)

-1
source

All Articles