James Gu
James Gu

Reputation: 1392

How to use singleton data in Objective C?

I tried to create a singleton to set and get a string between different views:

globalVar.h:

@interface globalVar : NSObject
{
    NSString *storeID;
}

+ (globalVar *)sharedInstance;
@property  (nonatomic, copy) NSString *storeID;
@end

globalVar.m:

#import "globalVar.h"

@implementation globalVar
@synthesize storeID;

+ (globalVar *)sharedInstance
{
       static globalVar *myInstance = nil;    

    if (nil == myInstance) {
        myInstance  = [[[self class] alloc] init];        
    }
    return myInstance;
}
@end

Now how do I actually use the string? Say I want to set it to "asdf" in one view and load the "asdf" in another view.

Upvotes: 0

Views: 799

Answers (2)

rob mayoff
rob mayoff

Reputation: 386038

First, you need to change how you create your instance. Do it like this:

+ (GlobalVar *)sharedInstance
{
    static GlobalVar *myInstance;
    @synchronized(self) {
        if (nil == myInstance) {
            myInstance = [[self alloc] init];
        }
    }
    return myInstance;
}

You do not want to use [self class], because in this case self is already the globalVar class.

Second, you should name the class GlobalVar with a capital G.

Third, you will use it like this:

[GlobalVar sharedInstance].storeID = @"STORE123";
NSLog(@"store ID = %@", [GlobalVar sharedInstance].storeID);

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225232

To set it, do something like:

[globalVar sharedInstance].storeID = @"asdf";

And to use it:

NSString *myString = [globalVar sharedInstance].storeID;

Upvotes: 5

Related Questions