ref –
http://stackoverflow.com/questions/4965048/static-variables-in-objective-c-what-do-they-do
http://stackoverflow.com/questions/2649213/in-laymans-terms-what-does-static-mean-in-java
OBJECTIVE C STATIC VARIABLES
In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program.
This is in contrast to automatic variables
- whose lifetime exists during a single function call
- and dynamically-allocated variables like objects, which can be released from memory when no longer used
More simply put, a static variable’s value is maintained throughout all function/method calls.
1 2 3 4 5 6 |
-(void)staticMethod { static int i = 0; i++; NSLog(@"%u", i); } |
1 2 3 4 5 |
Logic * myLogic = [[Logic alloc] init]; [myLogic staticMethod];//1 [myLogic staticMethod];//2 [myLogic staticMethod];//3 |
On the other hand
Say you have this:
1 2 3 4 5 6 |
int f(void) { int i = 5; i += 10; return i; } |
Every call to f() will return the value 15.
static variable to mimic class variables
In the context of Objective-C classes, static variables are often used to mimic class variables, as Objective-C does not have class variables (other languages, such as Java, do). For instance, say you want to lazily initialize an object, and only return that object. You might see this:
1 2 3 4 5 6 7 8 9 10 11 |
static MyObject *obj = nil; @implementation MyObject + (id)sharedObject { if (obj == nil) obj = [[MyObject alloc] init]; return obj; } @end |
obj will be initialized the first time classObject is called; subsequent invocations of classObject will return the same object. You could check this by logging the address of the object:
NSLog(@”obj is at %p”, [MyObject sharedObject]);
NSLog(@”obj is at %p”, [MyObject sharedObject]); // Will print the same address both times
Furthermore, obj will be visible to all methods in MyObject.
This technique is used to implemented singleton classes in Objective-C as well.
Static Variables in Java
static means that the variable or method marked as such is available at the class level. In other words, you don’t need to create an instance of the class to access it.
1 2 3 4 5 |
public class Foo { public static void doStuff(){ // does stuff } } |
So, instead of creating an instance of Foo and then calling doStuff like this:
1 2 |
Foo f = new Foo(); f.doStuff(); |
You just call the method directly against the class, like so:
1 |
Foo.doStuff(); |
There’s just one of it because it belongs to the class.
Thus, it should be mentioned that a static field is shared by all instances of the class, thus all see the same value of it.