Objective-C:如何声明一个对子类可见的静态成员?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/844958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C: how to declare a static member that is visible to subclasses?
提问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...
我声明了一系列处理通信协议的静态类。我想声明一个父类来处理常见的消息,比如 ACK、内联错误......
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
父母.m
@implementation ServerParser
static NSString * currentElement;
but the subclasses are not seing the currentElement.
但子类没有看到 currentElement。
回答by Alex Rozanski
If you declare a static variable in the implementation file of a class, then that variable is only visible to thatclass.
如果您在声明一个类的实现文件的静态变量,则该变量是只看到那个班。
You could declare the static variable in the header file of the class, however, it will be visible to all classes that #importthe header.
您可以在类的头文件中声明静态变量,但是,该头文件对所有类都是可见#import的。
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.
然而,除非其他类使用该方法,否则该变量将不可见。
回答by Морт
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.
一种解决方法是在父类的实现中声明静态变量,并在父类中声明一个属性。然后在访问器方法中访问静态变量。通过这种方式,您可以使用点语法访问静态变量,如属性。所有子类都访问相同的共享静态变量。
回答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{
公共抽象类基础:preBase{
//Inherit VariableStaticPrivate
//And you can use it.
}
}
public class DerivedOne : Base {
公共类 DerivedOne : Base {
//Also inherit VariableStaticPrivate
//And you can use it.
}
}

