First, what you are asking for is a global variable, a static is similar but a little bit different...
Putting a static
declaration outside of any @interface
in a header (.h
) file will create a different variable in each implementation (.m
) file you include the header in - not what you want in this case.
So static
on a declaration creates a variable whose lifetime is that of the whole application execution but which is only visible within the compilation unit (e.g. the implementation file) in which it appears - either directly or via inclusion.
To create a global variable visible everywhere you need to use extern
in the header:
extern NSString *id;
and in your implementation repeat the declaration without the extern
:
NSString *id;
As to what is wrong with global variable vs. class methods, that is a question on program design and maintainability. Here are just a few points to consider:
- With a method the value cannot be changed unless you provide a setter method as well as getter method. Variables are always read-write.
- Namespace pollution: a class method is only valid when paired with its class name (
[YourClass id]
); the variable name is valid everywhere it's included simply as id
; that both pollutes the name space and loses the connection between id
and YourClass
- which leads us to...
- Encapsulation: globals variables break strong encapsulation, and encapsulation aids program design and maintenance - this is a big topic.
That said, there can be a time and a place for globals, sometimes...
After question updated
A static
variable declared in the implementation is effectively a "class variable" - a variable shared by all instances of the class.
The pros'n'cons of a class variable vs. setter & getter class methods are exactly the same as the pros'n'cons of an instance variable vs. properties & setter/getter instance methods.
Class setters/getters allow for validation and other logic to be executed on each read/write; and localization of memory management - in short the abstraction and encapsulation benefits of any method.
Therefore whether you use a variable or a setter/getter depends on your application. It is the same question as whether you use an instance variable or setter/getter/property.