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

0 votes
asked May 10, 2009 by gonso

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.

2 Answers

0 votes
answered May 10, 2009 by alex-rozanski

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.

0 votes
answered May 15, 2014 by user3741883

More simple. Create a pre Base class, with protected static variable. For example:

public abstract class preBase {

protected static int VariableStaticPrivate;

}

public abstract class Base : preBase{

//Inherit VariableStaticPrivate
//And you can use it.

}

public class DerivedOne : Base {

//Also inherit VariableStaticPrivate
//And you can use it.

}

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...