Last active
July 8, 2022 01:20
-
-
Save romainmenke/468168b87de2131847cf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
What version of swift is this?