Singleton or single class - pros and cons

The search for global static will begin to set the color in one place, which will be used throughout the application. I could not understand some very good answers (older) about one singlet here on SO, so I created a class to handle this very simply. Based on some (from other threads), I decided to avoid the application delegate.

There seem to be several ways to handle this. As a low-performance ios / objective-c developer, what makes this method lower? (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 color:

cell.backgroundColor = [[[Global alloc] initWithColor:@"greenbackground"] myColor];

Edited for a 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 use:

cell.comboLabel.textColor = [[Global sharedGlobal] myGreen];
+3
source share
1 answer

, alloc init , . , (alloc + init), , .

alloc , myColor, , , .

:

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

All Articles