views:

2694

answers:

2

Hi

Im 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.

What am I doing wrong?

Thanks in advace. Gonso

+12  A: 

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.

Perspx
Thanks for the tip. I didn't think of the access method.Anyway, I ended changing the "static" class to an "instance" behaviour.
gonso
WOAWOAOWAWOA: if you declare a static variable in the header, and then import the header, each file (compilation unit, actually) importing the header will be referring to a DIFFERENT variable of the same name. So if you say (for instance) currentElement = [[element alloc] init]; in the super class initialization, and then try to get currentElement in a subclass, currentElement will still be nil to the subclass!
Jared P
A: 

A workaround would be to declare the static variable in the implementation of the parent class AND also declare a property in the parent class. Then in the accessor methods access the static variable. This way you can access static variables like properties with dot syntax. All the subclasses access the same shared static variable.

Морт