Singleton in Swift
import Foundation
let sharedInstance = AppSingleton();
final class AppSingleton{
var aSharedVariable:NSMutableString!
private init(){}
}
seen from China
seen from United Kingdom

seen from T1
seen from Azerbaijan
seen from China
seen from United States
seen from United States
seen from China
seen from China

seen from United States

seen from Malaysia

seen from Netherlands
seen from Türkiye
seen from Egypt
seen from United States
seen from T1
seen from United States
seen from China

seen from Saudi Arabia
seen from China
Singleton in Swift
import Foundation
let sharedInstance = AppSingleton();
final class AppSingleton{
var aSharedVariable:NSMutableString!
private init(){}
}
iOS: The singleton pattern
The Singleton Pattern is one of must used patterns in Objective-C.
If you are a Objective-C developer, of course you have seen the singleton pattern.
[UIApplication sharedApplication]
[NSBundle mainBundle]
[NSUserDefaults standardUserDefaults]
Do you know them?
they are class methods (they starts with "+"); they will return the (unique) shared instance of an object; they are singletons!
That's all!
Well, below is explained how to create a singleton for your custom class.
First sign your .h file with a class method +(id)sharedInstance;. It must return a object (id is ok!).
#import <Foundation/Foundation.h> @interface MyCustomClass : NSObject +(id)sharedInstance; @end
Second implement the +(id)sharedInstance method into the .m file. It will create the (shared) instance only one time and always return it.
+ (id)sharedInstance { static MyCustomClass *theSharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ theSharedInstance = [[self alloc] init]; }); return theSharedInstance; }
That's really all!
Don't forget: the singleton is also a whisky. We love singleton!