Are static variables in Objective-C methods shared across instances?

后端 未结 2 1855
余生分开走
余生分开走 2020-12-23 21:16

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:



        
相关标签:
2条回答
  • 2020-12-23 21:53

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

    - (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:

    i = 1 ; j = 1
    i = 1 ; j = 2
    i = 1 ; j = 3
    i = 1 ; j = 4
    
    0 讨论(0)
  • 2020-12-23 21:57

    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).

    0 讨论(0)
提交回复
热议问题