I have a singleton declaration as follows :
@interface SomeGlobalData : NSObject
+ (instancetype) sharedInstance;
@property (nonatomic, assign) BOOL info;
@end
@implementation SomeGlobalData
+(instancetype)sharedInstance
{
static SomeGlobalData *sharedObj = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedObj = [[self alloc] init];
});
return sharedObj;
}
-(id)init
{
if (self = [super init]) {
info = false;
}
return self;
}
@end
-(void)_startSomeMethod
{
SomeGlobalData *obj = [SomeGlobalData sharedInstance];
//do stuff
obj.info = true;
}
-(void)_readStatus
{
SomeGlobalData *data = [SomeGlobalData sharedInstance];
NSLog(@"Start status = %d", data.info);
}
-(void)_dummyMethodForUnderstanding
{
[self _readStatus];
[self _startSomeMethod];
[self _readStatus];
}
The output of calling dummyMethodForUnderstanding
should be
Start status = 0
Start status = 1
Is my understanding of singleton classes correct? I am worried that init is called every time sharedInstance
method gets called and I might end up accidentally re-initializing info
to false