David
David

Reputation: 3323

Singletons or Separate Class - Pros & Cons

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];

Upvotes: 3

Views: 345

Answers (1)

giorashc
giorashc

Reputation: 13713

Well, calling alloc and init all the time is wasteful if you want to use your color properties globally. This is where Singletons come to help in that you create it only ONCE (alloc + init) and than use it wherever you want in your code.

In your case alloc is called every time you want to read myColor which is wasteful considering you are going to use it throughout your code.

this looks much cleaner :

cell.backgroundColor = [[Global sharedInstance] myColor];

Upvotes: 1

Related Questions