为什么我的实例变量在Objective C中表现得像静态/类/全局变量?

时间:2016-11-21 21:21:39

标签: objective-c

我在Objective C中定义了一个类,它的一个实例变量就像一个静态变量/类变量/全局变量。我的意思是当我创建类的第二个实例时,实例变量已经初始化,当我在第二个实例中更改变量时,第一个实例也会更改,就好像变量实际上不是实例变量一样。

这是我的代码:

#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;
}

此处显示出现该错误消息的执行:

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

1 个答案:

答案 0 :(得分:3)

要将变量定义为实例变量,您必须根据此答案https://stackoverflow.com/a/13573236/2848676将其包装在花括号中。

需要对这些线进行修正:

@implementation MyObject 

int _value;

将_value定义为实例变量的正确方法如下:

@implementation MyObject {

int _value;

}

这会产生正确的输出:

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

并且没有报告错误。