I'm declaring a family of static classes that deals with a communications protocol. I want to declare a parent class that process common messages like ACKs, inline errors...
I need to have a static var that mantain the current element being processed and I want to declare it in the parent class.
I do it like this:
parent.m
@implementation ServerParser static NSString * currentElement;
but the subclasses are not seing the currentElement.
We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class.
According to Static data members on the IBM C++ knowledge center: The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope.
The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.
The reason for this is simple, static members are only declared in a class declaration, not defined. They must be explicitly defined outside the class using the scope resolution operator. If we try to access static member 'a' without an explicit definition of it, we will get a compilation error.
If you declare a static variable in the implementation file of a class, then that variable is only visible to that class.
You could declare the static variable in the header file of the class, however, it will be visible to all classes that #import
the header.
One workaround would be to declare the static variable in the parent class, as you have described, but also create a class method to access the variable:
@implementation ServerParser static NSString *currentElement; ... + (NSString*)currentElement { return currentElement; } ... @end
Then, you can retrieve the value of the static variable by calling:
[ServerParser currentElement];
Yet the variable won't be visible to other classes unless they use that method.
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