开发者

How to define non string constants in objective-C? [duplicate]

开发者 https://www.devze.com 2023-01-22 09:07 出处:网络
This question already has answers here: How do I define constant values of UIColor? 开发者_JAVA技巧(9 answers)
This question already has answers here: How do I define constant values of UIColor? 开发者_JAVA技巧 (9 answers) Closed 7 years ago.

I can define global strings like this:

// .h
extern NSString * const myString;

// .m
NSString * const myString = @"String";

Now I need to define UIcolor similarly, How can I do it?

I'm trying:

// .h
extern UIColor * const myColor;

// .m
UIColor * const myColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];

But it doesn't work, I'm getting error: initializer element is not constant

Thanks


You can't initialize global variables with method calls (or any expression which is not a compile time constant). It works with your @"String" example because that is a constant expression. No code needs to be called to evaluate it.


Strings are a special case, unfortunately. For any other type of object, you will have to initially set it to nil and then provide a value on launch. A good place to do this is in a related class's initialize method (not to be confused with the instance init method), which is guaranteed to be called at least once before the class is instantiated. (Note I said "at least once"; it might be called again depending on the class hierarchy, so check if your globals are nil before you assign them new values.)


One thing that works is:

static UIColor *DefaultColor = nil;

+ (void) initialize {
    static BOOL initiliazed = NO;
    if (initialized)
        return;
    DefaultColor = [UIColor blackColor];
    initialized = YES;
}

But of course it’s quite ugly if you just want to initialize a single color.

0

精彩评论

暂无评论...
验证码 换一张
取 消