Dailycode.info

Short solution for short problems

Global Variables using the Singleton Pattern (IOS)

As a .Net developer, I'm used to work with the Singleton pattern. This can come in very handy, also for caching purposes. Although it can be dangerous to just put in large amount of data on the client. Keeping this in mind, I created a Global Variables Store as a Singleton to store the apps global settings. I started by creating an objective C class. called it: VariableStore. The header of the class looks like this:

//

//  VariableStore.h

//  GALVASFIAPP01

//

//  Created by Mark Deraeve on 25/09/12.

//  Copyright (c) 2012 __Galvapower__. All rights reserved.

//

 

#import <UIKit/UIKit.h>

 

@interface VariableStore : NSObject

 

{

    NSString *MESuploadPath;

    NSString *MESwebservicesPath;

    NSString *MESPlant;

    NSString *MESWorkPlace;

    

}

 

+ (VariableStore *) sharedInstance;

 

@property (nonatomic, retain) NSString *MESUploadPath;

@property (nonatomic, retain) NSString *MESwebservicesPath;

@property (nonatomic, retain) NSString *MESPlant;

@property (nonatomic, retain) NSString *MESWorkPlace;

 

@end

 

Then the implementation file looks like this:

 

//

//  VariableStore.m

//  GALVASFIAPP01

//

//  Created by Mark Deraeve on 25/09/12.

//  Copyright (c) 2012 __Galvapower__. All rights reserved.

//

 

#import "VariableStore.h"

 

@implementation VariableStore

 

@synthesize MESPlant=_MESPlant;

@synthesize MESUploadPath=_MESUploadPath;

@synthesize MESWorkPlace=_MESWorkPlace;

@synthesize MESwebservicesPath=_MESwebservicePath;

 

+ (VariableStore *) sharedInstance

{

    static VariableStore *myInstance = nil;

    

    if (nil == myInstance)

    {

        myInstance = [[[self class] alloc] init];

        myInstance.MESUploadPath =@"http://server/FileUpload/upload.php";

    }

    return myInstance;

}

 

 

@end

 

 

Now you can use these variables anywhere in your application if you import the VariableStore header file. You can do this like following:

#import "VariableStore.h"

...

[[VariableStoresharedInstance] setMESUploadPath:@"http://server/FileUpload/upload.php"];

or to get a value:

NSString *urlString = [[VariableStoresharedInstance] MESUploadPath];