I don't quite understand static variables when defined in the implementation of an interface. In methods I do understand how they differ from local variables, but not when defined directly in an implementation.
Look at these examples. What difference do these two make practically?
#include "MyClass.h" @implementation MyClass int myInt; ... @end
And:
#include "MyClass.h" @implementation MyClass static int myInt; ... @end
myInt
is in both cases visible to all the methods, and if I interpreted a test I ran correctly, myInt
will in both cases be the same variable for different instances of the class.
In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program.
No you cannot have non-static variables in an interface. By default, All the members (methods and fields) of an interface are public. All the methods in an interface are public and abstract (except static and default).
Interface variables are static because java interfaces cannot be instantiated on their own. The value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned.
The variable with a static keyword is declared inside a function is known as a static local variable. The scope of the static local variable will be the same as the automatic local variables, but its memory will be available throughout the program execution.
Unfortunately, it has different effects depending on where you use it.
Static Functions:
By default, all functions have a global scope. The static specifier lets you limit the function’s scope to the current file.
Static Local Variables:
When you use the static modifier on a local variable, the function “remembers” its value across invocations. For example, the currentCount variable in the following snippet never gets reset, so instead of storing the count in a variable inside of main(), we can let countByTwo() do the recording for us.
// main.m #import <Foundation/Foundation.h> int countByTwo() { static int currentCount = 0; currentCount += 2; return currentCount; } int main(int argc, const char * argv[]) { @autoreleasepool { NSLog(@"%d", countByTwo()); // 2 NSLog(@"%d", countByTwo()); // 4 NSLog(@"%d", countByTwo()); // 6 } return 0; }
This use of the static keyword does not affect the scope of local variables.
Read more about the static keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With