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

查看:97
本文介绍了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的initialize方法. 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天全站免登陆