Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

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:

- (void) myMethod {     static int myVar = 0; } 
like image 720
iter Avatar asked Jul 07 '10 21:07

iter


People also ask

Are static variables shared between instances?

Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class. Static variable is like a global variable and is available to all methods. Non static variable is like a local variable and they can be accessed through only instance of a class.

Are static methods shared?

3. The static Fields (or Class Variables) In Java, when we declare a field static, exactly a single copy of that field is created and shared among all instances of that class.

Is a static variable shared by all objects of the class?

Class Variables and MethodsA static variable is shared by all instances of a class. Only one variable created for the class.

Are static variables shared between threads C?

Each thread will share the same static variable which is mostly likely a global variable.


2 Answers

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 
like image 91
Mike Avatar answered Sep 22 '22 02:09

Mike


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

like image 20
Carl Norum Avatar answered Sep 23 '22 02:09

Carl Norum