Some time We may need to create object which can be accessible through all the applications. In those situation we need to create a global Variable.

You should create a Model class of subclass NSObject.

Screen Shot 2016-07-12 at 12.56.34 AM.png

Two files will be created Model.h and Model.m.

Now go to Model.h and declare a Method

#import <Foundation/Foundation.h>

@interface Model : NSObject

@property(nonatomic,strong) NSString myString;

+(Model*)getSharedInstance;

@end

Now go to Model.m and define the Method

#import “Model.h”

@implementation Model

static Model *instance = nil;

+(Model *)getSharedInstance

{

    @synchronized(self)

    {

        if(instance==nil)

        {

            instance= [Model new];

        }

    }

    return instance;

}

@end

Now in Your ViewController

Model *sharedInsatnce=[Model getSharedInstance];  

sharedInstance.myStrong= @”I am Global variable. Please use me”;

Enjoy Coding 🙂

Advertisements