0

I need to use the same color in a bunch of files so I decided to make "global variables" to do it. I created an NSObject class called ColrClass and implemented some class methods like this:

+(UIColor *) returnRedColor {

    UIColor *redColr = [UIColor colorWithRed:0 green:0.433 blue:0.804 alpha:1];

    return redColr;

}

So my question, is there any other way to do the same? I would like to use the most rational solution, but not sure that these class methods would be the best. Am I wrong and it is a nice solution? Or are there any better solutions?

rihekopo
  • 3,241
  • 4
  • 34
  • 63
  • http://stackoverflow.com/questions/27980756/different-uicolor-for-different-uilabels-through-application-in-ios – timgcarlson Jan 16 '15 at 20:00

2 Answers2

3

You could make a category on UIColor to do this. The file name would look something like UIColor+ColorClass. The category would look like this:

UIColor+ColorClass.h

#import <UIKit/UIKit.h>

@interface UIColor (ColorClass)
+ (UIColor *)returnRedColor;
@end

UIColor+ColorClass.m

#import "UIColor+ColorClass.h"

@implementation UIColor (ColorClass)
+ (UIColor *)returnRedColor 
{
    return [UIColor colorWithRed:0 green:0.433 blue:0.804 alpha:1];
}
@end

Then in your ProjectName-prefix.pch you can do #import "UIColor+ColorClass.h to have this method available throughout the entire project. The method call would be [UIColor returnRedColor];

keithbhunter
  • 12,258
  • 4
  • 33
  • 58
  • 1
    `ColorClass` isn't an appropriate name for a category. Instead consider something like `XYZAdditions` (assuming your project prefix is *XYZ*). Also, instead of naming the method `returnRedColor`, consider naming it `redColor`, in accordance with Cocoa naming guidelines. – jlehr Jan 16 '15 at 20:11
0

I prefer to use a singleton instance instead of class methods in situation like this. I think it's better because you can override the methods when it's necessary.

/* ... */
static ColrClass* sharedInstance = nil;
// Get the shared instance and create it if necessary.
+(ColrClass*) sharedInstance {
    if ( sharedInstance == nil ) {
        sharedInstance = [ColrClass new];
    }
    return sharedInstance;
}
/* ... */

-(UIColor *) returnRedColor {

    UIColor *redColr = [UIColor colorWithRed:0 green:0.433 blue:0.804 alpha:1];

    return redColr;

}

and use like this:

[[ColrClass sharedInstance] returnRedColor];
szpetip
  • 333
  • 6
  • 12
  • If it's a singleton, how, and in what circumstances would you override the methods? – jlehr Jan 16 '15 at 20:14
  • You can use like this: ColrClass *colrInstance = [AnyColrClassSublass sharedInstance]. This is the way how you can keep the singletons and change the implementation. – szpetip Jan 16 '15 at 20:17