Started looking around for a global static, to set a color in one place, to be used throughout an app. I couldn't understand some very good answers (older) about the singleton here on SO, so I created a class to very simply handle this. Based on some (of the other threads), I decided to avoid the app delegate.
There seems to be several ways to handle this. As a low experience ios/objective-c developer, what does the method below miss? (It works, by the way and seems simple.)
// Global.h
@interface Global : NSObject
@property (strong, nonatomic) UIColor *myColor;
- (id)initWithColor:(NSString *)color;
// Global.m
@implementation Global
@synthesize myColor;
- (id)initWithColor:(NSString *)color
{
if (!self) {
self = [super init];
}
if ([color isEqualToString:@"greenbackground"])
myColor = [[UIColor alloc] initWithRed:0.0 / 255 green:204.0 / 255 blue:51.0 / 204 alpha:1.0];
... and so on with other colors
return self;
}
@end
Later to use the color:
cell.backgroundColor = [[[Global alloc] initWithColor:@"greenbackground"] myColor];
Edited for better solution:
// Global.h
#import <foundation/Foundation.h>
@interface Global : NSObject {
UIColor *myGreen;
UIColor *myRed;
}
@property (nonatomic, retain) UIColor *myGreen;
@property (nonatomic, retain) UIColor *myRed;
+ (id)sharedGlobal;
@end
// Global.m
#import "Global.h"
static Global *sharedMyGlobal = nil;
@implementation Global
@synthesize myGreen;
@synthesize myRed;
#pragma mark Singleton Methods
+ (id)sharedGlobal {
@synchronized(self) {
if (sharedMyGlobal == nil)
sharedMyGlobal = [[self alloc] init];
}
return sharedMyGlobal;
}
- (id)init {
if (self = [super init]) {
myGreen = [[UIColor alloc] initWithRed:0.0 / 255 green:204.0 / 255 blue:51.0 / 204 alpha:1.0];
myRed = [[UIColor alloc] initWithRed:204.0 / 255 green:51.0 / 255 blue:51.0 / 204 alpha:1.0];
}
return self;
}
@end
And usage:
cell.comboLabel.textColor = [[Global sharedGlobal] myGreen];