Objective-C: how to declare a static member that i

2019-01-23 03:10发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

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.

}