开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜