xcode +(void) 在objective-c 类静态变量构造函数中初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3042973/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:27:36  来源:igfitidea点击:

+(void) initialize in objective-c class static variables constructor

iphoneobjective-cxcodeinterfaceconstructor

提问by Sagar R. Kothari

I found some sample code from here.

我从这里找到了一些示例代码。

static UIImage *backgroundImageDepressed;

/**
 *
 */
@implementation DecimalPointButton

+ (void) initialize {
    backgroundImageDepressed = [[UIImage imageNamed:@"decimalKeyDownBackground.png"] retain];
}

Is it something like this - +(void) initializemethod initialize static variables of a class ( interface ) in Objective C? I have never seen this before.

是不是像这样 -+(void) initialize方法在目标 C 中初始化类(接口)的静态变量?我以前从未见过这个。

回答by kennytm

This +initializemethod is described in The Objective-C Programming Language.

+initialize方法在The Objective-C Programming Language 中有所描述。

The runtime system sends an initializemessage to every class object before the class receives any other messagesand after its superclass has received the initializemessage. This gives the class a chance to set up its runtime environment before it's used. If no initialization is required, you don't need to write an initializemethod to respond to the message.

运行时系统在类接收任何其他消息之前和其超类收到 消息之后,initialize向每个类对象发送一条消息。这使类有机会在使用之前设置其运行时环境。如果不需要初始化,则不需要编写响应消息的方法。initializeinitialize

For example, when [DecimalPointButton alloc]is called, the runtime will check if [DecimalPointButton initialize]has been called. If not, it will +initializethe class. This ensure the backgroundImageDepressedimage is ready beforeany instances of DecimalPointButton are constructed.

例如,当[DecimalPointButton alloc]被调用时,运行时将检查是否[DecimalPointButton initialize]已被调用。如果没有,它将+initialize上课。这可确保在构建任何 DecimalPointButton 实例之前backgroundImageDepressed图像已准备就绪。