In Objective-C one can make a singleton that does not have a sharedInstance or similar class call simply by making the -init
method reference the status singleton variable, like so
static MyObject *sharedObject;
/*
* The init will return the actual singleton instance if called directly.
* The first time called it will create it and intialize it.
*/
- (instancetype)init
{
static dispatch_once_t once;
dispatch_once(&once, ^{
id myself = [super init];
if (nil != myself) {
[self initialize];
sharedObject = myself;
}
});
return sharedObject;
}
So a user could call this MyObject *myObject = [[MyObject alloc] init];
as many times as he wanted and would get the same object back each time. But it is not obviously, from syntax, a singleton.
I am trying to get a similar functionality in Swift, where I can return the same object each time (an NSObject subclass) but so that it is not obviously a singleton.
I would call it var myObject = MyObject()
or when bridging to Objective-C as above but they would all reference the same object.
I am familiar with the normal sharedInstance method of singleton in Swift.
Suggestions on how to do this would be appreciated.
This is not the same as the dispatch_once in Swift answers as that still uses a sharedInstance