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

seen from Germany
seen from United States
seen from Israel

seen from Poland
seen from United States

seen from Israel
seen from United States
seen from Austria
seen from Japan

seen from United Kingdom

seen from United States
seen from Poland

seen from Austria
seen from United States
seen from South Korea
seen from Poland
seen from Germany
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!