Objective-C 静态类级别变量 [英] Objective-C Static Class Level variables

查看:40
本文介绍了Objective-C 静态类级别变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 Film,每个类都存储一个唯一的 ID.在 C#、Java 等中,我可以定义一个静态 int currentID,每次我设置 ID 时,我都可以增加 currentID,并且更改发生在类级别而不是对象级别.这可以在Objective-C中完成吗?我发现很难找到答案.

I have a class Film, each of which stores a unique ID. In C#, Java etc I can define a static int currentID and each time i set the ID i can increase the currentID and the change occurs at the class level not object level. Can this be done in Objective-C? I've found it very hard to find an answer for this.

推荐答案

问题描述:

  1. 您希望 ClassA 具有 ClassB 类变量.
  2. 您正在使用 Objective-C 作为编程语言.
  3. Objective-C 不像 C++ 那样支持类变量.

另一种选择:

使用 Objective-C 特性模拟类变量行为

Simulate a class variable behavior using Objective-C features

  1. 在 classA.m 中声明/定义一个静态变量,这样它就只能被 classA 方法(以及你放在 classA.m 中的所有东西)访问.

  1. Declare/Define an static variable within the classA.m so it will be only accessible for the classA methods (and everything you put inside classA.m).

覆盖 NSObject 的初始化类方法,用 ClassB 的实例只初始化一次静态变量.

Overwrite the NSObject initialize class method to initialize just once the static variable with an instance of ClassB.

您会想知道,为什么我要覆盖 NSObject 初始化方法.关于此方法的 Apple 文档给出了答案:运行时恰好在该类或从它继承的任何类从程序内部发送其第一条消息之前,向程序中的每个类发送初始化一次.(因此,如果不使用该类,则该方法可能永远不会被调用.)".

You will be wondering, why should I overwrite the NSObject initialize method. Apple documentation about this method has the answer: "The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.)".

随意在任何 ClassA 类/实例方法中使用静态变量.

Feel free to use the static variable within any ClassA class/instance method.

代码示例:

文件:classA.m

file: classA.m

static ClassB *classVariableName = nil;

@implementation ClassA

...
 
+(void) initialize
{
    if (! classVariableName)
        classVariableName = [[ClassB alloc] init];
}

+(void) classMethodName
{
    [classVariableName doSomething]; 
}

-(void) instanceMethodName
{
    [classVariableName doSomething]; 
}

...

@end

参考资料:

  1. 比较目标的类变量解释-C 和 C++ 方法

这篇关于Objective-C 静态类级别变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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