Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdavalos1993/be764f08b2c9512bb3347894dbea1194 to your computer and use it in GitHub Desktop.
Save mdavalos1993/be764f08b2c9512bb3347894dbea1194 to your computer and use it in GitHub Desktop.
class Singleton {
// singelton pattern
private static var privateShared : Singleton?
class func shared() -> Singleton {
// make sure we get an instance from the singleton queue
guard let uwShared = read(privateShared) else {
privateShared = Singleton()
return privateShared!
}
return uwShared
}
func destoy() {
// make sure we write on the singleton queue and halt reads
write {
Singleton.privateShared = nil
}
}
private let singletonQueue = dispatch_queue_create("SingletonQueue", DISPATCH_QUEUE_CONCURRENT)
private static let singletonQueue = dispatch_queue_create("SingletonQueue", DISPATCH_QUEUE_CONCURRENT)
// attributes
private var somePrivateAttribute : Int = 0
var someAttribute : Int {
get {
return read(somePrivateAttribute)
}
set(value) {
write {
self.somePrivateAttribute = value
}
}
}
private init() {
print("init singleton")
}
}
// instance read / write
extension Singleton {
private func write(closure:() -> Void) {
dispatch_barrier_sync(singletonQueue) {
closure()
}
}
private func read<T>(value:T) -> T {
var returnValue : T = value
dispatch_sync(singletonQueue) {
returnValue = value
}
return mainQueue(returnValue)
}
private func mainQueue<T>(value:T) -> T {
var returnValue : T = value
dispatch_sync(dispatch_get_main_queue()) {
returnValue = value
}
return returnValue
}
}
// type read / write
extension Singleton {
private static func write(closure:() -> Void) {
dispatch_barrier_sync(singletonQueue) {
closure()
}
}
private static func read<T>(value:T) -> T {
var returnValue : T = value
dispatch_sync(singletonQueue) {
returnValue = value
}
return mainQueue(returnValue)
}
private static func mainQueue<T>(value:T) -> T {
var returnValue : T = value
dispatch_sync(dispatch_get_main_queue()) {
returnValue = value
}
return returnValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment