Using a dispatch_once create a Singleton model in Swift
The traditional Objective-C approach in Swift to create a Singleton model.
One of the toughest issues to debug is the one created by the multiple instances of a class which manages the state of a single resource. It is highly desirable if we can use some Design Pattern to control the access to that shared resource. The Singleton pattern fits the bill perfectly to solve this scenario; by wrapping a singleton class around this problem ensures that there will be only one instance of the class at any given time. A most common and clichéd example for a singleton class is the one used for logging purposes where the whole application needs only one logger instance at anytime
If you opt for the lazy instantiation paradigm, then the singleton variable will not get memory until the property or function designated to return the reference is first called. This type of instantiation is very helpful if your singleton class is resource intense.
class Global: NSObject {
var arrayDaysName: NSMutableArray! = []
class var sharedInstance : Global {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : Global? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = Global()
}
return Static.instance!
}
}
How to use?, It simple
Global.sharedInstance.arrDaysForecast = //Do what you want
No comments:
Post a Comment