Question

I have a iPad application where I'm attempting to use a singleton. This is the code in the .h file:

//-------------------------------------------
//--  singleton: timeFormat
@interface SingletonTimeFormat : NSObject  {
}
@property (nonatomic, retain) NSNumber *timeFormat;

+ (id)sharedTimeFormat;
@end

This is the code from the .m file:

//-------------------------------------------
//--  SingletonTimeFormat
@implementation SingletonTimeFormat  {

}

@synthesize timeFormat;

//--  sharedColorScheme  --
+ (id)sharedTimeFormat  {

static dispatch_once_t dispatchOncePredicate = 0;
__strong static id _sharedObject = nil;
dispatch_once(&dispatchOncePredicate, ^{
    _sharedObject = [[self alloc] init];
});

return _sharedObject;
}

-id) init {
self = [super init];
if (self) {
    timeFormat = [[NSNumber alloc] init];
}
return self;
}

@end

I load the value (either 12 or 24) in AppDelegate - didFinishLaunchingWithOptions, then when I want to get the value of timeFormat I use this:

SingletonTimeFormat *stf = [[SingletonTimeFormat alloc]init];
if([stf.timeFormat isEqualToNumber: [NSNumber numberWithInt:12]]) {

which returns 0 (it was set correctly in AppDelegate, but apparently when I do the alloc in another class, it loses it's value. So obviously it's not working! (I have several other singletons that have the same pattern, but so far they appear to be working.

What's wrong here and how do I fix it?

Was it helpful?

Solution

You don't want to call your singleton using alloc init. With this singleton, all references to it should be through its sharedTimeFormat method, which will init the object if necessary, and will return the singleton instance otherwise.

In other words, it doesn't appear that you're referencing the instance of the object stored in the static sharedObject variable, which means that it's stored value will not necessarily be the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top