Reputation: 3786
Here is a simple one for you guys . I'm defining a class to store variables in so I can reuse those variables in different ViewControllers .
Here is how I do it, it`s obviously not working ( that's why I'm asking a question ... ):
I declare a class :
VariableStore.h
@interface VariableStore : NSObject {
int evTe;
}
@property (nonatomic) int evTe;
+ (VariableStore *)shareInstance;
@end
VariableStore.m
@implementation VariableStore
@synthesize evTe;
+ (VariableStore *)sharedInstance {
static VariableStore *myInstance = nil;
return myInstance;
}
@end
Now in my FirstViewController I want to set the value for evTe :
[[VariableStore sharedInstance] setEvte:2];
NSLog(@"value testing, %i", evTe);
And this keeps on returning 0 unfortunately, Im obviously missing something important here but I can't figure out what it is .
Later on I
d like to set the value for evTe here in the FirstViewController and then reuse it back in the SecondViewController ..
Upvotes: 0
Views: 373
Reputation: 696
First, you have to declare the static variable outside the function, in a way both controllers can access.
static VariableStore* myInstance = nil;
The singleton sharedInstance should be:
if(myInstance == nil)
{
myInstance = [[VariableStore] alloc] init];
}
return myInstance;
Upvotes: 0
Reputation: 8990
Well, you're asking for the value of evTe without calling the object to which it belongs. Try this:
NSLog(@"value testing, %i", [[VariableStore sharedInstance] evTe]);
If you keep using the singleton for a number of times, you might want to do:
VariableStore *vStore = [VariableStore sharedInstance];
so you can do:
[vStore setEvTe:2];
NSLog(@"value testing, %i", [vStore evTe]);
And look out for what Matt said about nilling your singleton ;)
Upvotes: 2
Reputation: 949
I think in nslog you should output not just evTe, but [[VariableStore sharedInstance] evTe].
Upvotes: 1
Reputation: 24466
You are setting your shared instance to nil and then returning it:
static VariableStore *myInstance = nil;
return myInstance;
A nil instance won't hold your variable. It's nil.
First off you shouldn't be using a singleton to pass around variables. If you're going to do that then you might as well just use global variables instead (don't do that either by, the way). Second, if you insist on using a singleton, you need to read up on how to use them.
Finally, if you want to pass variables between view controllers, you either need another view controller that is a parent to the two to facilitate passing data between them, or one needs to call the other and take the first one or its data as a parameter.
Upvotes: 4