Objective-C:如何声明一个对子类可见的静态成员? [英] Objective-C: how to declare a static member that is visible to subclasses?

查看:107
本文介绍了Objective-C:如何声明一个对子类可见的静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在声明一系列处理通信协议的静态类。我想声明一个处理常见消息的父类,如ACK,内联错误...

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

我需要一个静态var来保存当前处理的元素而我想要在父类中声明它。

I need to have a static var that mantain the current element being processed and I want to declare it in the parent class.

我这样做:

parent.m

@implementation ServerParser

static NSString * currentElement;

但是子类没有查看currentElement。

but the subclasses are not seing the currentElement.

推荐答案

如果在类的实现文件中声明静态变量,那么该变量仅对 类可见。

If you declare a static variable in the implementation file of a class, then that variable is only visible to that class.

您可以在类的头文件中声明静态变量,但是,对于 #import 标题的所有类都可以看到它。

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.

这篇关于Objective-C:如何声明一个对子类可见的静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆