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

2019-01-23 03:06发布

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.

3条回答
够拽才男人
2楼-- · 2019-01-23 03:21

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.

查看更多
Evening l夕情丶
3楼-- · 2019-01-23 03:27

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.

查看更多
仙女界的扛把子
4楼-- · 2019-01-23 03:29

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.

}

查看更多
登录 后发表回答