Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: how to declare a static member that is visible to subclasses?

Tags:

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.

like image 768
gonso Avatar asked May 10 '09 08:05

gonso


People also ask

How do we declare a member of a class static?

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.

Is it possible to define a static member outside 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.

Can a static member access a class object?

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.

Can we define a static member only within a class declaration?

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.


1 Answers

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.

like image 179
Alex Rozanski Avatar answered Sep 27 '22 19:09

Alex Rozanski