objective-c方法中的静态变量

时间:2023-01-02 20:01:27

I want to clarify whether different instances of an Objective-C class share static variables that occur inside methods, or if each instance gets its own copy:

我想澄清一下Objective-C类的不同实例是否共享在方法内发生的静态变量,或者每个实例是否都有自己的副本:

- (void) myMethod {
    static int myVar = 0;
}

2 个解决方案

#1


30  

It's the same as a static variable in C; the instances will share the variable. If you want each instance to have its own copy, you want an instance variable (declared in the @interface block).

它与C中的静态变量相同;实例将共享变量。如果希望每个实例都有自己的副本,则需要一个实例变量(在@interface块中声明)。

#2


78  

Static locals are shared between method calls AND instances. You can think of them as globals which are visible only inside their methods:

静态本地在方法调用AND实例之间共享。您可以将它们视为仅在其方法中可见的全局变量:

- (void) showVars {
    int i = 0;
    static int j = 0;
    i++; j++;
    NSLog(@"i = %i ; j = %i", i, j);
}

[...]

[...]

[obj1 showVars];
[obj2 showVars];
[obj1 showVars];
[obj2 showVars];

Above calls on 2 different instances will output:

以上调用将输出2个不同的实例:

i = 1 ; j = 1
i = 1 ; j = 2
i = 1 ; j = 3
i = 1 ; j = 4

#1


30  

It's the same as a static variable in C; the instances will share the variable. If you want each instance to have its own copy, you want an instance variable (declared in the @interface block).

它与C中的静态变量相同;实例将共享变量。如果希望每个实例都有自己的副本,则需要一个实例变量(在@interface块中声明)。

#2


78  

Static locals are shared between method calls AND instances. You can think of them as globals which are visible only inside their methods:

静态本地在方法调用AND实例之间共享。您可以将它们视为仅在其方法中可见的全局变量:

- (void) showVars {
    int i = 0;
    static int j = 0;
    i++; j++;
    NSLog(@"i = %i ; j = %i", i, j);
}

[...]

[...]

[obj1 showVars];
[obj2 showVars];
[obj1 showVars];
[obj2 showVars];

Above calls on 2 different instances will output:

以上调用将输出2个不同的实例:

i = 1 ; j = 1
i = 1 ; j = 2
i = 1 ; j = 3
i = 1 ; j = 4