Ok, still re-adjusting to things when switching between C, C++, C# and Objective-C so sometimes my head spins. This time however, I'm more confused as to the proper way since I have seen at least three different ways to declare static variables in Objective-C, and there's a fourth if you consider it's just a superset of C itself. So which of these is right?
If we want to share a stand-alone variable (i.e. not a static class variable, but one just defined in a header) is that done the same way as in 'C' (ala with 'extern' in the header?)
Foo.h
@interface Foo : NSObject{
static int Laa;
}
@end
Foo.m
@implementation Foo
...
@end
Foo.h
@interface Foo : NSObject{
}
@end
Foo.m
static int Laa; // <-- Outside of the implementation
@implementation Foo
...
@end
Foo.h
@interface Foo : NSObject{
}
@end
Foo.m
int Laa; // <-- Note no word 'static' here like in 'Option B'
@implementation Foo
...
@end
Foo.h
static int Laa;
@interface Foo : NSObject{
}
@end
Foo.m
@implementation Foo
...
@end
Foo.h
@interface Foo : NSObject{
}
@end
Foo.m
@implementation Foo
static int Laa;
...
@end
Do you have to use the word extern
or is that only when you are using .c/.c++ files, not .m/.mm files?
C++ Programming Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
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.
Static is a keyword used in C programming language. It can be used with both variables and functions, i.e., we can declare a static variable and static function as well. An ordinary variable is limited to the scope in which it is defined, while the scope of the static variable is throughout the program.
In C, static variables can only be initialized using constant literals.
The Option A is wrong. Objective -c class doesn't have a static variable.
Option B and E are the correct way to implement static variables.
Option C creates a global variable that might be accessed out side the implementation file using extern keyword.
Option D again creates a global static variable which can be accessed from anywhere by just importing .h file.
About your bonus question: extern keyword has the same meaning as in C/C++.
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