0

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.

2 Answers 2

5

To set it, do something like:

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

And to use it:

NSString *myString = [globalVar sharedInstance].storeID; 
Sign up to request clarification or add additional context in comments.

2 Comments

for set, i got an error "Receiver type 'globalVar' for instance message does not declare a method with selector 'setstoreID:"
@James sorry - I changed my answer to use Objective-C 2.0 accessors. You must have tried before I made the switch.
1

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.