I have defined a class in Objective C and one of its instance variables is acting like a static variable / class variable / global variable. What I mean is when I create a second instance of the class, the instance variable is already initialized and when I change the variable in the second instance, the first instance also changes, as if the variable is not really an instance variable.
Here's my code:
#import <Foundation/Foundation.h>
@interface MyObject : NSObject
- (int)getValue;
- (void)setValue:(int)aValue;
@end
@implementation MyObject
int _value;
- (int)getValue {
return _value;
}
- (void)setValue:(int)aValue {
_value = aValue;
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
MyObject *myObject1 = [MyObject new];
printf("myObject1 value before assignment: %d\n", [myObject1 getValue]);
[myObject1 setValue:1];
printf("myObject1 value after assignment: %d\n", [myObject1 getValue]);
MyObject *myObject2 = [MyObject new];
printf("myObject2 value before assignment: %d\n", [myObject2 getValue]);
[myObject2 setValue:2];
printf("myObject2 value after assignment: %d\n", [myObject2 getValue]);
if (1 != [myObject1 getValue]) {
printf("ERROR: myObject1 value should be 1 after assignment of myObject2 value but is %d\n", [myObject1 getValue]);
}
[pool drain];
return 0;
}
Here's the execution showing that that error message occurs:
myObject1 value before assignment: 0
myObject1 value after assignment: 1
myObject2 value before assignment: 1
myObject2 value after assignment: 2
ERROR: myObject1 value should be 1 after assignment of myObject2 value but is 2