1

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
Michael Osofsky
  • 11,429
  • 16
  • 68
  • 113

1 Answers1

3

To define a variable as an instance variable you have to wrap it in curly braces according to this answer https://stackoverflow.com/a/13573236/2848676.

The correction needs to be made to these lines:

@implementation MyObject 

int _value;

The correct way to define _value as an instance variable is like this:

@implementation MyObject {

int _value;

}

This produces the correct output:

myObject1 value before assignment: 0
myObject1 value after assignment: 1
myObject2 value before assignment: 0
myObject2 value after assignment: 2

And no error is reported.

Community
  • 1
  • 1
Michael Osofsky
  • 11,429
  • 16
  • 68
  • 113
  • 1
    To clarify a bit here: the reason that your variable was acting as a `static` variable was because it was -- when you define variables within the `@implementation` braces, the variable is added as an instance variable; otherwise, it is defined as any other C variable with the appropriate duration (and in this case, the default rules say that this variable is `static`). It is the same as if you had placed `int _value;` outside of the `@implementation` entirely. – Itai Ferber Nov 22 '16 at 03:42