views:

474

answers:

3

Hi,

I have a iPhone application with a few custom-defined colors for my theme. Since these colors will be fixed for my UI, I would like to define the colors in a class to be included (Constants.h and Constants.m). How do I do that? (Simply defining them does not work because UIColors are mutable, and would cause errors - Initalizer not constant).

/* Constants.h */
extern UIColor *test;

/* Constants.m */
UIColor *test = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];

Thanks!

+2  A: 

A UIColor is not mutable. I usually do this with colors, fonts and images. You could easily modify it to use singletons or have a static initializer.

@interface UIColor (MyProject)

+(UIColor *) colorForSomePurpose;

@end

@implementation UIColor (MyProject)

+(UIColor *) colorForSomePurpose { return [UIColor colorWithRed:0.6 green:0.8 blue:1.0 alpha:1.0]; }

@end
drawnonward
-1 for the first sentence - the Initializer is what is not constant, not the instance. For all intents and purposes, UIColor could (or could tomorrow) contain internal state variables which are unexposed to the user, making them seem to us constant, however there is nothing in Obj-C forcing this. Therefore the compiler cannot use a static initializer, like it would like to, because [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0] is a method call, and thus the results of this cannot be put in the text segment, which is created at compile time.
Jared P
Mutable means that you can change the instance. Immutable means you cannot change the instance. Constant means that the instance cannot be changed. A UIColor is not mutable and also not constant. Only CFString/NSString has truly constant instances because they are handled specially as part of the language by the compiler.
drawnonward
A: 

Often people put global constants into singleton objects - or as drawnonward noted, you can make them accessible via a class method of some class.

Kendall Helmstetter Gelner
A: 

Use the AppController to make the colors accessible globally, rather than a static variable. That way it makes sense from an architecture standpoint, and also if you wanted to hypothetically change color schemes, even while running, this would just be a method or two on the AppController

Jared P