I want to have a static variable in Cocoa.
After looking at How do I declare class-level properties in Objective-C?, I am unclear whether there is anything wrong with what I have always done so far, i.e.
// Foo.m
static NSString* id;
@interface Foo ()
instead of
// Foo.h
@interface Foo {
}
+(NSString*) id;
// Foo.m
+(NSString*) id
{
static NSString* fooId = nil;
if (fooId == nil)
{
// create id
}
return fooId;
}
Obviously, the second approach offers an opportunity for initializing the id. But if I initialize the id myself somewhere else in the code, within, say a getter:
-(NSString*) getId
{
if (id==nil) {
id = ... // init goes here
}
return id;
}
Then is there anything wrong with the simple static declaration approach as opposed to the more complex class function approach? What am I missing?
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:
[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...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.
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