+(void) 在 Objective-C 类静态变量构造函数中初始化

问题描述 投票:0回答:1

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

static UIImage *backgroundImageDepressed;

/**
 *
 */
@implementation DecimalPointButton

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

是这样的 -

+(void) initialize
方法初始化 Objective C 中类(接口)的静态变量吗?我以前从未见过这个。

iphone objective-c xcode interface constructor
1个回答
17
投票

+initialize
方法在The Objective-C Runtime中进行了描述。

运行时系统在类接收任何其他消息之前

以及其超类收到
initialize消息之后,向每个类对象发送initialize
消息。这使类有机会在使用之前设置其运行时环境。如果不需要初始化,就不需要写 
initialize
 方法来响应消息。

例如,当调用

[DecimalPointButton alloc]

 时,运行时将检查 
[DecimalPointButton initialize]
 是否已被调用。如果没有,班级将会
+initialize
。这确保了
backgroundImageDepressed
图像在构造DecimalPointButton的任何实例之前
准备就绪。

© www.soinside.com 2019 - 2024. All rights reserved.