I have a static variable that i want to access from another class in the same project in X-Code. I have declared it in the .h file AND the .m file, gave it a value, and then when i accessed the other class, i got an error message saying that:
"Property 'xx' is not found on object of type 'yy'"
i declared the variable as extern in the .h, and redeclared it as the variable type in the .m. I have tried to change it to static in the .h, but it still doesn't work. And yes, i have imported the file containing the variable, in case that is the problem.
Can anyone help me?
EDIT:
this is the code that i'm currently using:
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 went to the second version, the variable anObject in destination.h can be accessed, but its value is not 2, it's 0. I want it to follow the one i declared in source.h.
A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables.
Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
Accessibility of the Static Variables in Java. Static variables can be accessed by calling the class name of the class. There is no need to create an instance of the class for accessing the static variables because static variables are the class variables and are shared among all the class instances.
I am assuming the static variable declared in the .h file is outside the @interface
. So something like:
static NSString *myObjectTest = @"Test";
@interface MyObject : NSObject
@end
If that is the case then you will not be able to access it using something like:
MyObject *obj = [[MyObject alloc] init];
[obj myObject]
or
obj.myObject
That is what is giving you the "Property 'xx' is not found on object of type 'yy'". That static variable is not a property on the object of MyObject.
That static variable is accessible like so myObjectTest
as long as you import the .h file
Update See Chuck's comment below why this is a bad idea to do this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With