views:

67

answers:

4

Hi guys,

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

+1  A: 

Don't know exactly why that happens but this question might help you out with a solution.

Norling Jr.
Ok, thank you, I picked accepted answer from there
Burjua
+4  A: 

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.

Ferruccio
A: 

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.

zoul
You can get rid of that BOOL and just check if DefaultColor is nil.
benzado
or use `dispatch_once()` and don't bother checking anything :)
Graham Lee
Ohó, I didn’t know about `dispatch_once`, thanks.
zoul
+2  A: 

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.)

benzado
Variables with static storage duration are automatically initialised.
dreamlax
@dreamlax Yes they are.
benzado