Globals and Singletons

My preferred approach to creation and maintaing global variables/ constants is by singletons and singleton instance[s]. Not only is an elegant method that adds compliance to a very important Cocoa design pattern, but also provides you a lot of flexibility.
Moreover — using singletons — your code won’t get cluttered and managing globals will be much easier.
For example, consider a class [ala_crossref]Globals[/ala_crossref], that I created to maintain global variables in one of my past Cocoa Touch projects:

@interface Globals : NSObject {
NSString *attributeKey;

+ (Globals *)sharedInstance;

– (NSString *)getAttributeKey;
– (void)setAttributeKey:(NSString *)attrK;

And implementation:

#import "Globals.h"

@implementation Globals

static Globals *_sharedInstance;

– (id)init {
if (self = [super init]) {
attributeKey = @"";
return self;

+ (Globals *)sharedInstance {
if (!_sharedInstance) {
_sharedInstance = [[Globals alloc] init];
return _sharedInstance;

– (NSString *)getAttributeKey {
return attributeKey;
– (void)setAttributeKey:(NSString *)attrK {
attributeKey = attrK;

Author: AP

Lasă un răspuns

Adresa ta de email nu va fi publicată.