Logan Serman
Logan Serman

Reputation: 29870

What is the best practice for declaring a global variable in an iOS app?

Suppose I have a UIColor that I want to use across every view controller to tint it's title/navigation bar. I was wondering what is the best way to declare such a property. Should I declare it as a member of the application delegate? Create a model class for global properties, and declare a static function + (UIColor)getTitleColor? Pass the UIColor object to every view controller? Is there another method that I did not describe, that is viewed as being the best way to go about this?

Upvotes: 2

Views: 869

Answers (2)

J2theC
J2theC

Reputation: 4452

By what you are trying to do, I think you could do it much easier by using appearance. You can assign different colors to all of your different types of interface elements. Check the UIAppearance protocol for more information.

If this is not what you want, then I would suggest @rob mayoff answer: using a category.

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385500

There are lots of ways to do this. I like to do it by putting a category on UIColor:

UIColor+MyAppColors.h

@interface UIColor (MyAppColors)

+ (UIColor *)MyApp_titleBarBackgroundColor;

@end

UIColor+MyAppColors.m

#import "UIColor+MyAppColors.h"

@implementation UIColor (MyAppColors)

+ (UIColor *)MyApp_titleBarBackgroundColor {
    static UIColor *color;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        color = [UIColor colorWithHue:0.2 saturation:0.6 brightness:0.7 alpha:1];
    });
    return color;
}

@end

Then I can use it by importing UIColor+MyAppColors.h in any file that needs the title bar background color, and calling it like this:

myBar.tintColor = [UIColor MyApp_titleBarBackgroundColor];

Upvotes: 6

Related Questions